哪一个selectwaitpid / wait / waitid?

在fork之后我想在subprocess中使用execl。 execl将执行脚本,这将需要大约120秒的时间。 我尝试了几乎所有与waitpid,waitid和waitid不同的参数(0,WNOHANG等)的组合,但是在所有情况下我都得到了-1的返回值。 所以我想知道在什么时候我需要使用哪个等待函数? 所以我可以集中在一个等待function,使其工作。

我从我的日志中观察到的一个更有趣的事情是,当我在subprocess中什么都不做时,它显示我的父线程是孤立的。 我不知道怎么可能? 我的父母线程如何成为孤儿?

#include <errno.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> int main(void) { pid_t Checksum_pid = fork(); if (Checksum_pid < 0) printf("Fork Failed\n"); else if (Checksum_pid == 0) { execl("/bin/ls","ls",(char *)NULL) ; exit(EXIT_FAILURE); } else { int childStatus; pid_t returnValue = waitpid(Checksum_pid, &childStatus, 0); if (returnValue > 0) { if (WIFEXITED(childStatus)) printf("Exit Code: %d\n", WEXITSTATUS(childStatus)); } else if (returnValue == 0) printf("Child process still running\n"); else { if (errno == ECHILD) printf(" Error ECHILD!!\n"); else if (errno == EINTR) printf(" Error EINTR!!\n"); else printf("Error EINVAL!!\n"); } } return 0; } 

正如我所说:你最后的else应该是

  else perror("waitpid"); 

但是你正在得到ECHILD 。 所以请阅读waitpid(2)手册页:

  ECHILD (for wait()) The calling process does not have any unwaited- for children. ECHILD (for waitpid() or waitid()) The process specified by pid (waitpid()) or idtype and id (waitid()) does not exist or is not a child of the calling process. (This can happen for one's own child if the action for SIGCHLD is set to SIG_IGN. See also the Linux Notes section about threads.) 

顺便说一句,我不能重现你的错误。 检查你的极限,由ulimit -a在bash上给出。

也许你的execl失败(特别是如果你执行一些脚本而不是/bin/ls )。 之后添加一个调用perror

另外,使用gcc -Wall -g编译并使用stracegdb