关于c语言捕获信号的问题。

新手上路,请多包涵

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.

阅读 1.6k
1 个回答

如果多个SIGCHLD同时到达(在其中一个处理时,相同的到达),,它们会被压缩为同一个....

所以如果父进程希望知道多个子进程结束,更优雅的做法是

while(1)
{
    pid_t pid = waitpid(-1, NULL, 0);
    if (pid <=0)
       break;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进