23,217
社区成员




void test_wait()
{
printf("parent=%d\n", getpid());
if (fork() == 0) {
printf("child1=%d\n", getpid());
sleep(3);
printf("exit child1\n");
exit(1);
}
if (fork() == 0) {
printf("child2=%d\n", getpid());
sleep(5);
printf("exit child2\n");
exit(2);
}
while (1) {
int stat;
int c = wait(&stat);
int err = errno;
if (c < 0) perror("wait");
printf("child=%d, exit=%x, err=%d\n", c, stat, err);
if (c < 0)
break;
}
}
int main()
{
//test 1
test_wait();
//test 2
signal(SIGCHLD, SIG_IGN);
test_wait();
}
//test1
parent=876
child1=877
child2=878
exit child1 <-- 3秒
child=877, exit=100, err=0 <-- 3秒,父进程第一次wait返回
exit child2 <-- 5秒
child=878, exit=200, err=0 <--- 5秒,父进程第二次wait返回
wait: No child processes
child=-1, exit=200, err=10 <--- 5秒,父进程第三次wait失败
//test2
parent=876
child1=881
child2=882
exit child1 <-- 3秒
exit child2 <-- 5秒
wait: No child processes
child=-1, exit=0, err=10 <--- 5秒,父进程第一次wait失败
POSIX.1-2001 specifies that if the disposition of SIGCHLD is set to SIG_IGN or
the SA_NOCLDWAIT flag is set for SIGCHLD (see sigaction(2)), then children
that terminate do not become zombies and a call to wait() or waitpid() will block
until all children have terminated, and then fail with errno set to ECHILD.