6 int mysystem(const char *cmdstring)
7 {
8 //实现system()函数,需要fork()函数,exec()函数,waitpid()函数
9 pid_t pid;
10 int status;
11 if(cmdstring == NULL)//如果命令字符串为空,返回1
12 return 1;
13 pid = fork();//创建子进程
14 if(pid < 0)
15 return -1;
16 else if(pid == 0)
17 {
18 //加载shell,由shell执行命令,如果执行失败,子进程返回127
19 if(execl("/bin/sh", "sh", "-c", cmdstring, NULL) == -1)
20 _exit(127);
21 }
22 if(waitpid(pid, &status, 0) == -1)
23 status = -1;
24 return status;
25 }