代码如下:
#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;
}
输出如下:
自由互联热门推荐:PDF电子发票识别软件,一键识别电子发票并导入到Excel中!10大顶级数据挖掘软件!人工智能的十大作用!

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