this is my code
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<signal.h>
#include<unistd.h>
void handler1(int sig) {
int pid;
if ((pid = waitpid(-1, NULL, 0)) < 0)
printf("waitpid error");
printf("Handler reaped child %d\n", pid);
sleep(1);
}
int main() {
int i, n;
if (signal(SIGCHLD, handler1) == SIG_ERR) {
printf("signal error\n");
}
for (i = 0; i < 3; ++i) {
if (fork() == 0) {
printf("Hello from child %d\n", getpid());
exit(0);
}
}
// sleep(1);
printf("Father love you!\n");
while (1);
exit(0);
}
When I run it, it shows this :
Father love you!
Hello from child 7843
Hello from child 7844
Hello from child 7842
Handler reaped child 7842
But I think it should be
Father love you!
Hello from child 7843
Hello from child 7844
Hello from child 7842
Handler reaped child 7842
Handler reaped child 7843
There a repetition of Handler reaped child xx.
If I uncomment sleep(1);, it will show what i want :
Hello from child 7858
Handler reaped child 7858
Hello from child 7859
Hello from child 7860
Handler reaped child 7859
Father love you!
I dont know why the first one has only one Handler reaped child. Please help me, thank you in advence.
如果多个SIGCHLD同时到达(在其中一个处理时,相同的到达),,它们会被压缩为同一个....
所以如果父进程希望知道多个子进程结束,更优雅的做法是