如果我使用
我正在尝试以下代码,似乎子进程完成后的退出状态信息至少在几秒钟内是有效的,但我不知道有效时间有多长,也不知道如何通知操作系统我不会再次调用
fork
创建了一个子进程,并且在父进程调用waitpid
之前子进程退出,那么由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
调用失败了。我没有考虑到这一点!谢谢你指出来。 - Daniel Trebbien