我试图在使用 fork() 并行运行两个命令时获取子进程。我使用以下代码执行此操作:
int process() {
int w, status;
while ((w = waitpid(-1,&status,WNOHANG)) > 0)
fprintf(stderr,"Completed: %d (%d)\n",w,status);
int pid;
if ((pid = fork()) < 0)
errorExit (EXIT_FAILURE);
if (pid == 0) {
// run first command
} else if (cmdList->right) {
// run second command
}
}
我对这段代码的理解是:我在程序运行时持续运行 waitpid()
,并且每当 waitpid()
返回大于 0 的值时,它报告它(从而允许僵尸死亡),然后执行 fprintf()
到 stderr
。这种理解有错吗?
最佳答案
此代码将确保删除所有终止的子项,如标志所示:
WNOHANG
The waitpid() function shall not suspend execution of the calling thread if status is not immediately available for one of the child processes specified by pid.
所以当你遇到这类 child 时,你就会执行fprintf()
。因此,如果您有两个这样的子级,则 fprintf()
将执行两次。 fprintf()
将写入 stderr
。
请注意,在执行该循环之后,您将再次调用 fork()
,这将创建一个子级,该子级不会由循环处理。
关于c - 使用 fork() 时收割子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26986657/