//* Named Pipes in Posix - producer/writer *

#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 /** open the pipe for writing */ // some systems require use popen instead of open // and would create the pipe without use of mkfifo if ( (pipe = open(PIPE_NAME, O_WRONLY)) == -1) { fprintf(stderr,"Pipe failed"); return 1; } /** use the pipe */ while(1) { fgets(buffer, sizeof(buffer), stdin); // warning: on Linux fgets does not remove the final '\n' // fputs(buffer, pipe); int byteswritten = write(pipe, buffer, strlen(buffer)); if (strlen(buffer)==1) break; } /** close the pipe */ 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; }