/* twin2.c -- One of two programs that use named pipes (or FIFOs) * The other program is twin1.c. * After you have compiled both programs into images twin1 * and twin2, execute both in the background passing * as only parameter the name you want to use for the fifo. * For example, you could use the name * named_pipe_fifo * Twin1 will write to twin2 two lines from a * limerick. Twin2 will read from the fifo and print out the * info. * Whichever twin you launch first, it will * hang in there until the other twin is launched. Then * the communication takes place and both twins die. */ #include #include #include #include #include #include #include #define MAXBUFFER 256 #define FIFO_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ) /* Default protection mode of fifo so that all can read only I can write */ int main(int argc, char *argv[]) { int fd; char buffer[MAXBUFFER]; int len; if (argc <2) { printf("usage: twin1 name-of-fifo\n"); exit(0); } if ((mkfifo(argv[1],FIFO_MODE)<0) && (errno != EEXIST)) { perror("mkfifo"); exit(0); } if ((fd = open(argv[1], O_RDONLY))<0) { perror("open"); exit(0); } while ((len=read(fd,buffer, MAXBUFFER-1))>0) { buffer[len] = '\0'; printf("%s", buffer); } close(fd); return 0; }