Pipeline communication pipe() experiment

The parent process creates two child processes, and the child processes pass messages to the parent process through pipes. The parent process reads child process 1 first, then child process 2.

 1 #include <sys/wait.h>
 2 #include <sys/types.h>
 3 #include <unistd.h>
 4 #include <iostream>
 5 #include <cstdlib>
 6 #include <signal.h>
 7 #include <string>
 8 using namespace std;
 9 int flag;
10 void foo (int signo) {
11     flag = 0;
12 }
13 int main() {
14     int fp[2];
15     pid_t pid1, pid2;
16     string InPipe;
17     string OutPipe;
18     while ( pipe(fp) < 0 );
19     if ( (pid1 = fork()) < 0 ) {
20         cout << "pid1 error" << endl;
21         return -1;
22     }
23     if (pid1 == 0) {
24         flag = 1;
25         signal(16, foo);
26         while(flag);
27         close(fp[0]);
28         InPipe = "C1";
29         write(fp[1], InPipe.c_str(), InPipe.length()+1);
30         sleep(1);
31         exit(0);
32     }
33     else {
34         if ( (pid2 = fork()) < 0 ) {
35             cout << "pid2 error" << endl;
36             return -1;
37         }
38         if (pid2 == 0) {
39             flag = 1;
40             signal(17, foo);
41             while(flag);
42             close(fp[0]);
43             InPipe = "C2";
44             write(fp[1], InPipe.c_str(), InPipe.length()+1);
45             sleep(1);
46             exit(0);
47         }
48         else {
49             sleep(5);
50             char c = '0';
51             close(fp[1]);
52             kill(pid1, 16);
53             waitpid(pid1, 0, 0);
54             OutPipe.clear();
55             while (read(fp[0], &c, 1) && c != '\0')
56                 OutPipe += c;
57             cout << OutPipe << endl;
58             kill(pid2, 17);
59             waitpid(pid2, 0, 0);
60             OutPipe.clear();
61             c = '0';
62             while (read(fp[0], &c, 1) > 0 && c != '\0')
63                 OutPipe += c;
64             cout << OutPipe << endl;
65             exit(0);
66         }
67     }
68     return 0;
69 }

Send a signal to tell the two child processes to write data to the pipe, wait until the child process ends, and then read from the pipe.

Swap L52 and L53 with L58 and L59 respectively, so that process 1 is read first, and then process 2 is read.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324820813&siteId=291194637