多进程失败拉起的demo

 1 #include <iostream>
 2 #include <vector>
 3 #include <unistd.h>
 4 #include <stdlib.h>
 5 #include <stdio.h>
 6 #include <string.h>
 7 #include <signal.h>
 8 #include <sys/wait.h>
 9 #include <errno.h>
10 
11 void RunChild(int idx) {
12     for (int i = 0; i < 10; i++) {
13         printf("worker %d %d
", getpid(), idx);
14         sleep(1);
15     }
16 }
17 
18 int main() {
19     int worker_cnt = 10;
20     std::vector<int> worker_pids(worker_cnt);
21     for (int i = 0; i < worker_cnt; i++) {
22         int pid = fork();
23         if(pid != 0) {
24             //no process < 0 ?
25             worker_pids[i] = pid;
26             continue;
27         }
28 
29         RunChild(i);
30         exit(0);
31     }
32 
33     //avoid some unkown action for SIGCHLD
34     signal(SIGCHLD, SIG_DFL);
35     while (true) {
36         //1.get exit child 
37         //2.get worker by pid
38         //3.fork it
39         //4.child run
40 
41         //1.get exit child 
42         int pid = -1;
43         while((pid = wait(NULL)) == -1) {
44             if (errno == EINTR) {
45                 printf("wait pid err %d %s
", errno, strerror(errno));
46                 continue;
47             }
48             else {
49                 break;
50             }
51         }
52         if(pid == -1) {
53             printf("wait pid err %d %s
", errno, strerror(errno));
54             //sleep( 1 );
55             continue;
56         }
57         printf("wait pid %d
", pid);
58 
59         //2.get worker by pid
60         int worker_id = -1;
61         for (int i = 0; i < worker_cnt; i++) {
62             if (worker_pids[i] == pid) {
63                 worker_id = i;
64                 break;
65             }
66         }
67         printf("worker pid %d id %d exit
", pid, worker_id);
68         if( worker_id == -1 ) {
69             printf("master wait pid %d not worker
", pid);
70             continue;
71         }
72 
73         //3.fork it
74         usleep(100000);
75         pid = fork();
76         if (pid != 0) {
77             // no process pid < 0 ?
78             printf("%s new worker id %d
", __func__, pid);
79             worker_pids[worker_id] = pid;
80             continue;
81         }
82 
83         //4.child run
84         RunChild(worker_id);
85         exit(0);
86     }
87     return 0;
88 }

 这里有个问题,父进程退出了,子进程还没退出。解决方案是在RunChild中调用:

1 void RunChild(int idx) {
2     prctl(PR_SET_PDEATHSIG, SIGHUP);
3     for (;true;) {
4         printf("worker %d %d
", getpid(), idx);
5         sleep(1);
6     }
7 }

可以查看下man 2 prctl。

https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits/284443

原文地址:https://www.cnblogs.com/linyx/p/9816623.html