开发者社区> 问答> 正文

父进程捕获到子进程挂掉的信号以后又创建了一个子进程,但是子进程不执行后边的算法?

想法:在主函数中创建多个进程处理后边的任务,然后如果创建的子进程有一个挂掉了,那么父进程捕获到子进程挂掉的信号,立即fork重新创建子进程然后接着处理后边的任务。

但是实际测试的结果是,子进程挂掉后,父进程会再创建子进程,但是创建的子进程不会处理任务,不知道是为什么?

主函数中的创建进程代码:
screenshot

展开
收起
a123456678 2016-06-14 11:31:12 3218 0
2 条回答
写回答
取消 提交回答
  • https://github.com/ideal

    首先,在父进程,只要执行一次signal(SIGCHLD, fork_child)就可以了,并不需要循环注册这个signal handler。

    另外,你在fork_child里,if (child_process == 0) { exit(0); },意味着fork出来的子进程马上exit,当然不会继续执行了。

    2019-07-17 19:37:06
    赞同 展开评论 打赏
  • #include <stdlib.h>
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <unistd.h>
     
    #define CHILD_SIZE 5
    #define BUF_SIZE 100
    static void child_process();
     
    int main()
    {
        int num_child = 0;
        pid_t pid;
        char buf[100];
        int count = 0;
        int n;
     
        while(1) {
            while (num_child < CHILD_SIZE && count < 20) {
                pid = fork();
                if (pid == 0) {
                    child_process();
                } else if (pid < 0) {
                    write(1, "ERR: fork()\n", sizeof("ERR: fork()\n")-1);
                    break;
                } else {
                    n = snprintf(buf, BUF_SIZE, "Process %d Created.\n", pid);
                    write(1, buf, n);
                }
                num_child++;
                count++;
            }
     
            pid = wait(NULL);
            if (pid == -1) break;
            n = snprintf(buf, BUF_SIZE, "Process %d End.\n", pid);
            write(1, buf, n);
            num_child--;
        }
        return 0;
    }
     
    static void child_process()
    {
        sleep(random()%5);
        exit(0);
    }
    2019-07-17 19:37:06
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
数据+算法定义新世界 立即下载
袋鼠云基于实时计算的反黄牛算法 立即下载
Alink:基于Apache Flink的算法平台 立即下载