如果我fork
一个子进程,并且子进程在父呼叫waitpid
之前退出,那么由waitpid
设置的退出状态信息仍然有效吗?如果是这样,它何时变得无效;即如何确保我可以在子pid上调用waitpid
并在任意时间后继续获取有效的退出状态信息,以及如何“清理”(告诉操作系统我不再对退出完成的子进程的状态信息)?对于已经退出的子进程,waitpid是否会生成有效的状态信息?
我在玩弄下面的代码,看起来退出状态信息在儿童完成后至少有效几秒钟,但我不知道多长时间或如何通知操作系统,我不会再次调用waitpid
:孩子退出后
#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Failed to fork\n");
return EXIT_FAILURE;
}
else if (pid == 0) { // code for child process
_exit(17);
}
else { // code for parent
sleep(3);
int status;
waitpid(pid, &status, 0);
waitpid(pid, &status, 0); // call `waitpid` again just to see if the first call had an effect
assert(WIFEXITED(status));
assert(WEXITSTATUS(status) == 17);
}
return EXIT_SUCCESS;
}
确实,第二个'waitpid'调用确实失败。我没有想到这个!感谢您指出这一点。 – 2010-05-19 13:22:18