danielhilst

fifo.c

Oct 23rd, 2014
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 0 0
  1. /**
  2.  * desc: Fifo example, writes and reads depending on invocation name
  3.  * compile: gcc -o fifo-read fifo.c; ln -svf fifo-read fifo-write
  4.  */
  5. #include <errno.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <sys/types.h>
  10. #include <fcntl.h>
  11. #include <sys/types.h>
  12. #include <sys/stat.h>
  13.  
  14. #define BUF_LEN 256
  15. static char buf[BUF_LEN];
  16.  
  17. #define FIFO "MyFifo"
  18.  
  19. int main(int argc, char **argv)
  20. {
  21.         int pipe_fd;
  22.         int rval;
  23.         int n;
  24.         fd_set rfds;
  25.  
  26.         rval = mkfifo(FIFO, 0777);
  27.        
  28.         if (rval != 0)
  29.                 fprintf(stderr, "Cannot create fifo ERROR: %s\n", strerror(errno));
  30.  
  31.  
  32.         if (!strncmp("fifo-read", argv[0], 9)) {
  33.                 do  {
  34.                         puts("read");
  35.                         pipe_fd = open(FIFO, S_IRUSR);
  36.                         if (pipe_fd < 0) {
  37.                                 fprintf(stderr, "Cannot open fifo\n");
  38.                                 exit(EXIT_FAILURE);
  39.                         }
  40.                         while ((n = read(pipe_fd, buf, BUF_LEN)) > 0) {
  41.  
  42.                                 printf("\"%*s\"\n", n, buf);
  43.                         }
  44.                         close(pipe_fd);
  45.                 } while (1);
  46.         } else if (!strncmp("fifo-write", argv[0], 10)) {
  47.                 do {
  48.                         puts("read");
  49.                         pipe_fd = open(FIFO, S_IWUSR);
  50.                         if (pipe_fd < 0) {
  51.                                 fprintf(stderr, "Cannot open fifo\n");
  52.                                 exit(EXIT_FAILURE);
  53.                         }
  54.                         while ((n = read(0, buf, BUF_LEN)) > 0) { /* 0 == stdin */
  55.                                 write(pipe_fd, buf, n);
  56.                         }
  57.  
  58.                         close(pipe_fd);
  59.                 } while (1);
  60.         } else {
  61.                 fprintf(stderr, "Wrong program name, use fifo-write or fifo-read instead\n");
  62.                 return 0;
  63.         }
  64.  
  65.         return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment