Write two programs, one is to write data to the pipeline, and the other is to read the data to the pipe.
The creation of famous pipelines Mkfifo
Read data: FIFO_READ.C
/*FIFO_READ.C*/#include<sys/types.h>#include<sys/stat.h>#include<errno.h>#include<fcntl.h>#include<stdio.h>#include<stdlib.h>#include<limits.h>#defineMyfifo "/tmp/myfifo"/* Famous pipe file name */#defineMax_buffer_size PIPE_BUF/* defined in LIMITS.H */intMain () {CharBuff[max_buffer_size]; intFD; intnread; /*determine if a named pipe already exists, and if it has not yet been created, create it with the appropriate permissions*/ if(Access (Myfifo, F_OK) = =-1) { if(Mkfifo (Myfifo,0666) <0) && (errno! =eexist)) {printf ("cannot create FIFO file\n"); Exit (1); } } /*Open a named pipe as read-only blocking*/FD=Open (Myfifo, o_rdonly); if(FD = =-1) {printf ("Open FIFO file error\n"); Exit (1); } while(1) {memset (buff,0,sizeof(Buff)); if((nread = read (FD, buff, max_buffer_size)) >0) {printf ("Read '%s ' from fifo\n", Buff); }} close (FD); Exit (0);}
Write Data:
/*fifo_write.c*/#include<sys/types.h>#include<sys/stat.h>#include<errno.h>#include<fcntl.h>#include<stdio.h>#include<stdlib.h>#include<limits.h>#defineMyfifo "/tmp/myfifo"/* Famous pipe file name */#defineMax_buffer_size PIPE_BUF/* defined in LIMITS.H */intMainintargcChar* argv[])/*parameter is the string that will be written*/{ intFD; CharBuff[max_buffer_size]; intNwrite; if(ARGC <=1) {printf ("Usage:./fifo_write string\n"); Exit (1); } sscanf (argv[1],"%s", Buff); /*Open FIFO pipeline as write-only blocking*/FD=Open (Myfifo, o_wronly); if(FD = =-1) {printf ("Open FIFO file error\n"); Exit (1); } /*to write a string to the pipeline*/ if((Nwrite = write (fd, buff, max_buffer_size)) >0) {printf ("Write '%s ' to fifo\n", Buff); } close (FD); return 0;}
Pipeline communication of process communication