Implementing Pipeline Communication in Linux Environment

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main( )
{
    pid_t pid1,pid2;
    int pipe_fd[2];
    char w_buffer[100],r_buffer[100];     
    int    len1,len2;
    /* create a pipe */
    if(pipe(pipe_fd)<0)
    {
        printf("pipe create error\n");
        return -1;
    }
    /* create child process */
    if((pid1=fork( ))==0) // Subprocess 1 execution sequence
      {
        close(pipe_fd[0]); // The child process closes the read segment of the pipe first
        sprintf(w_buffer,"child 1 process is sending message!");
        len1 = strlen(w_buffer);
        write(pipe_fd[1],w_buffer,50); /*Write a string of len bytes to the pipe*/
        exit(0);
       }
     else if(pid1>0) // parent process execution sequence
      {
        waitpid(pid1,NULL,0); // Synchronization 1--wait for child process 1 to finish writing first        
        if((pid2=fork( ))==0) // Subprocess 2 execution sequence
        {
            close(pipe_fd[0]); // The child process closes the read segment of the pipe first
            sprintf(w_buffer,"child 2 process is sending message!");
            len2 = strlen(w_buffer);
            write(pipe_fd[1],w_buffer,50);
            exit(0);
         }
         else if(pid2>0) // parent process execution sequence
         {              
            waitpid(pid2,NULL,0); // Synchronization 2--wait for child process 2 to finish writing
            close(pipe_fd[1]); // The parent process closes the write segment of the pipe first
            /* Read a string of fixed length bytes from the pipe */
            if(read(pipe_fd[0],r_buffer,50)>0)   
                printf("%s\n",r_buffer);
            if(read(pipe_fd[0],r_buffer,50)>0)
                printf("%s\n",r_buffer);
            exit(0);
        }
      }
      return 0;
}
// waitpid function, wait for the child process to finish running before the parent process can run.
// Since the fork function allows the child process to completely copy the entire address space of the parent process, the child process has both the read and write ends of the pipe.
// So it's better to turn off the side that is not used in the relevant process.
// According to the requirements, "The parent process first receives the message from the child process P1, and then receives the message from the child process P2."
// There are two synchronization problems, between the two child processes and the parent process (first the child writes and then the parent reads), between the child process 1 and the child process 2 (first write 1, then 2 write)

Guess you like

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