system
来自APUE的Unix功能的实现:
图8.22
system
无需信号处理的功能
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
int
system(const char *cmdstring) /* version without signal handling */
{
pid_t pid;
int status;
if (cmdstring == NULL)
return(1); /* always a command processor with UNIX */
if ((pid = fork()) < 0) {
status = -1; /* probably out of processes */
} else if (pid == 0) { /* child */
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
_exit(127); /* execl error */
} else { /* parent */
while (waitpid(pid, &status, 0) < 0) {
if (errno != EINTR) {
status = -1; /* error other than EINTR from waitpid() */
break;
}
}
// if(waitpid(pid, &status, 0) < 0){
// if(errno != EINTR){
// status = -1;
// }
// }
}
return(status);
}
为什么使用while
循环waitpid
而不是if
在注释中添加语句?我尝试过,if
到目前为止没有发现任何错误。
除了子进程结束以外,waitpid
如果该函数被信号中断,则该函数可能会提前返回。如果确实如此,if
则不会输入该块,而是waitpid
会再次尝试。
没有循环,如果waitpid
被中断,您最终将处于父进程不等待子进程的状态,而当子进程退出时,您将陷入僵尸进程。直到父进程退出,该僵尸才会被清除,这时init进程成为父进程并自动等待僵尸。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句