Pipeline concept: Pipeline is based on file descriptor communication, when a pipeline is established, it will create two file descriptors fd[0] and fd[1], where fd[0] fixed for the read pipeline, and fd[1] fixed for the write pipeline, so that constitutes a half-duplex channel
Nameless Pipe: He can only be used for communication of kinship processes (that is, between parent-child processes or sibling processes), half-duplex communication is sent, read and write to it can use normal read (), write () and other functions.
Well-known pipeline: It can be two unrelated processes to communicate with each other. Can operate as normal files, follow Fifio.
1, create the Nameless pipe tube ()
Code Analysis:
/*pipe.c*/#include<unistd.h>#include<sys/types.h>#include<errno.h>#include<stdio.h>#include<stdlib.h>#defineMax_data_len 256#defineDelay_time 1intMain () {pid_t pid; intpipe_fd[2]; CharBuf[max_data_len]; Const CharData[] ="Pipe Test Program"; intReal_read, Real_write; memset ((void*) BUF,0,sizeof(BUF)); if(Pipe (PIPE_FD) <0)/*Creating Pipelines*/{printf ("Pipe Create error\n"); Exit (1); } if(PID = fork ()) = =0)/*Create a child process*/ { /*the child process closes the write descriptor and waits for the parent process to close the corresponding read descriptor by suspending the child process by 1 seconds*/Close (pipe_fd[1]); Sleep (Delay_time*3); /*child process reads pipeline contents*/ if(Real_read = Read (pipe_fd[0], buf, Max_data_len) >0) {printf ("%d bytes read from the pipe is '%s ' \ n", Real_read, buf); } Close (pipe_fd[0]);/*Close child process Read Descriptor*/Exit (0); } Else if(PID >0) { /*The parent process closes the read descriptor and waits for the child process to close the corresponding write descriptor by suspending the parent process for 1 seconds*/Close (pipe_fd[0]); Sleep (Delay_time); if(Real_write = Write (pipe_fd[1], data, strlen (data))! =-1) {printf ("Parent wrote%d bytes: '%s ' \ n", Real_write, data); } Close (pipe_fd[1]);/*Close Parent Process Write descriptor*/waitpid (PID, NULL,0);/*Collect child process exit information*/Exit (0); }}
Pipeline application of multi-process communication