#include <unistd.h>#include<sys/types.h>#include<sys/wait.h>#include<errno.h>#include<string.h>#include<stdio.h>#include<stdlib.h>intMain () {pid_t pid1,pid2; intpipe_fd[2]; Charw_buffer[ -],r_buffer[ -]; intLen1,len2; /*Create a pipeline*/ if(Pipe (PIPE_FD) <0) {printf ("Pipe Create error\n"); return-1; } /*Create Child process*/ if((Pid1=fork ()) = =0)//child process 1 execution sequence{Close (pipe_fd[0]);//the child process closes the read segment of the pipe firstsprintf (W_buffer,"Child 1 process is sending message!"); Len1=strlen (W_buffer); Write (pipe_fd[1],w_buffer, -);/*writes a string long as Len byte to the pipe*/Exit (0); } Else if(pid1>0)//parent Process Execution Sequence{waitpid (pid1,null,0);//synchronization, such as sub-process 1 first finish writing if((Pid2=fork ()) = =0)//child process 2 execution sequence{Close (pipe_fd[0]);//the child process closes the read segment of the pipe firstsprintf (W_buffer,"Child 2 process is sending message!"); Len2=strlen (W_buffer); Write (pipe_fd[1],w_buffer, -); Exit (0); } Else if(pid2>0)//parent Process Execution Sequence{waitpid (pid2,null,0);//synchronization 2--and so on 2 finishClose (pipe_fd[1]);//The parent process closes the write segment of the pipeline first /*reads a string of fixed-length bytes from a pipe*/ if(Read (pipe_fd[0],r_buffer, -) >0) printf ("%s\n", R_buffer); if(Read (pipe_fd[0],r_buffer, -) >0) printf ("%s\n", R_buffer); Exit (0); } } return 0;}//the Waitpid function waits for the child process to finish running before the parent process can run. //because the fork function allows the child process to completely copy the entire address space of the parent process, the child processes have read and write ends of the pipeline. //so it's best to turn off the unused end in the relevant process. //on demand, the parent process receives a message from the child process P1, and then receives the message from the child process P2. "//There are two synchronization issues, between two child processes and the parent process (the sub-write stepfather read), the child process 1, and the child Process 2 (first 1 write, then 2 write)
Implementation of pipeline communication in Linux environment-problem