linux下使用fork,exec,waitpid模拟system函数

代码如下:

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

inline int mySystem(const char *cmd) {
    pid_t pid;
    if(cmd == NULL)    return 1;
    int status;
    if((pid = fork()) < 0)   status = -1;
    else if(0 == pid) {
        execl("/bin/sh","sh","-c",cmd,(char*)0);
        _exit(127);
    }
    else {
        while(waitpid(pid, &status, 0) < 0)
            if(errno != EINTR)   return -1;
    }
    return status;
}

inline void test(const char *cmd) {
    int status;
    if((status = mySystem(cmd)) < 0) {
        puts("system error.");
        exit(0);
    }
    printf("exit status = %d\n", status);
}

int main() {
    test("date");
    test("nosuchcommand");
    test("who; exit 44");
    return 0;
}

输出如下:

 

  现在才知道系统的system函数为我们做了那么多的处理。

posted @ 2016-04-08 19:04  Newdawn_ALM  阅读(801)  评论(0编辑  收藏  举报