代码如下:
#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 ;
int status;
if((pid = fork()) < ) status = -;
else if( == pid) {
execl("/bin/sh","sh","-c",cmd,(char*));
_exit();
}
else {
while(waitpid(pid, &status, ) < )
if(errno != EINTR) return -;
}
return status;
} inline void test(const char *cmd) {
int status;
if((status = mySystem(cmd)) < ) {
puts("system error.");
exit();
}
printf("exit status = %d\n", status);
} int main() {
test("date");
test("nosuchcommand");
test("who; exit 44");
return ;
}
输出如下:
现在才知道系统的system函数为我们做了那么多的处理。