多进程失败拉起的demo

Posted linyx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多进程失败拉起的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 }

 

以上是关于多进程失败拉起的demo的主要内容,如果未能解决你的问题,请参考以下文章

在 Python 多处理进程中运行较慢的 OpenCV 代码片段

代码片段:Shell脚本实现重复执行和多进程

片段:java.lang.RuntimeException:传递结果ResultInfo失败

Windows之会话ID

线程学习知识点总结

python 自动拉起进程脚本