fifo_thread.c (1136B)
1 #include <fcntl.h> 2 #include <stdio.h> 3 #include <sys/stat.h> 4 #include <unistd.h> 5 #include <stdio.h> 6 #include <errno.h> 7 #include <string.h> 8 #include <pthread.h> 9 10 #define MAX_BUF 1024 11 12 char * myfifo = "./this.fifo"; 13 14 void * read_fifo() { 15 // open, read, and display the message from the FIFO 16 int fd = open(myfifo, O_RDONLY); 17 if (fd == -1) { 18 printf("read_fifo: %d", errno); 19 } 20 char buf[MAX_BUF]; 21 while (strcmp(buf, "exit")) { 22 int len = read(fd, buf, MAX_BUF); 23 printf("Received: %d bytes\n", len); 24 printf("Received: %s\n", buf); 25 if (!strcmp(buf, "exit")) { 26 printf("Should exit"); 27 } 28 } 29 close(fd); 30 } 31 32 int main() 33 { 34 int fd; 35 /* create the FIFO (named pipe) */ 36 mkfifo(myfifo, 0666); 37 /* open in nonblock to avoid waiting */ 38 pthread_t read_thread; 39 pthread_create(&read_thread, NULL, read_fifo, (void *) NULL); 40 fd = open(myfifo, O_WRONLY | O_ASYNC); 41 if (fd == -1) { 42 printf("main: %d\n", errno); 43 return 1; 44 } 45 /* write to the FIFO */ 46 char input[MAX_BUF]; 47 while (strcmp(input, "exit")) { 48 fgets(input, MAX_BUF, stdin); 49 write(fd, input, strlen(input)); 50 } 51 pthread_join(read_thread, NULL); 52 close(fd); 53 54 return 0; 55 }