//* Named Pipes in Posix - consumer/reader *

#include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #define BUFFER_SIZE 80 #define PIPE_NAME "mynamedpipe.pipe" int main(void) { char buffer[BUFFER_SIZE]; int pipe; /** create the pipe */ // Note: only the first program to run creates the pipe // in the second program to run this fails due to pipe already exist mkfifo(PIPE_NAME, 0666); // 0666 read and write access to any user process /** create the pipe */ if ( (pipe = open( PIPE_NAME, O_RDONLY)) == -1) { fprintf(stderr,"Pipe failed"); return 1; } /** read from the pipe until empty line or read fails */ while(1) { int bytesread = read(pipe,buffer,sizeof(buffer)-1); // reads up to the buffer size-1 for '\0' if (bytesread<0) break; // exit if reading fails buffer[bytesread]='\0'; // terminate the end of the string fprintf(stdout,"%s", buffer); if (strlen(buffer)==1) break; } close(pipe); /** delete the pipe if no longer needed */ // Note: the pipe will be actualy deleted when it is closed on both sides // Note: only one of the programs deletes the pipe // in the other program this fails due to pipe already deleted unlink(PIPE_NAME); return 0; }