APUE---system函数的简单实现

简单的system例子

#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>

int
system_test(const char* cmdstring)
{
    pid_t pid;
    int status;
    if (cmdstring == NULL)
        return 1;

    if ((pid = fork()) < 0) {  // error
        status = -1;
    } else if (pid == 0) { // son
        printf("[%s]\n", cmdstring);
        execl("/bin/sh", "sh", "-c", cmdstring, NULL);
    } else { // father
        while(waitpid(pid, &status, 0) < 0) {
            if (errno != EINTR) {
                status = -1;
                break;
            }
        }
    }
}

int main()
{
    char cmd[100] = {0};
    long tstamp = 166451600;
    snprintf(cmd, 100, "echo \"root: %ld\" > /tmp/time", tstamp * 1000);
    system_test(cmd);
}

关于fork()函数

#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
int
system_test(const char* cmdstring)
{
    pid_t pid;
    int status;

    if ((pid = fork()) < 0) {  // error
        status = -1;
    } else if (pid == 0) { // son
        printf("son [%d] \n",  getpid());
    } else { // father
        printf("father [%d] son [%d]\n", getpid(), pid);
        while(waitpid(pid, &status, 0) < 0) {
            if (errno != EINTR) {
                status = -1;
                break;
            }
        }
        printf("son exit\n");
    }
}


int main()
{
    char cmd[100] = {0};
    system_test(cmd);
}

打印:

pc123@ubuntu:~$ gcc maintest.cpp 
pc123@ubuntu:~$ ./a.out 
father [15385] son [15386]
son [15386] 
son exit
pc123@ubuntu:~$ 

上面的例子可以看出: 

  • fork返回值:

=0 : error ,

满足> 0条件:代表是父进程,其中的pid是子进程的进程号

满足< 0条件:代表是子进程。

  • waitpid操作

这个是用来给子进程收尸用的,当传入的第一个参数是>0的pid, 代表给进程号为pid的进程收尸。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值