my blog my blog

Tag: fork
Linux C编程—fork子程序以及fifo有名管道的使用

 

写一个程序,创建一个fifo有名管道,然后利用程序与子程序完成程序间的信息传输实例.

功能:输入什么,输出什么

           输入q或者Q程序退出

调用fifo文件:/tmp/fifo

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <unistd.h> 
  4. #include <sys/types.h> 
  5. #include <sys/stat.h> 
  6. #include <errno.h> 
  7. #include <fcntl.h> 
  8. #include <limits.h> 
  9.  
  10. #define FIFO_FILE "/tmp/fifo" 
  11. #define BUFFER_SIZE PIPE_BUF 
  12.  
  13. int main(void) { 
  14.     char buff[BUFFER_SIZE]; 
  15.  
  16.     if (access(FIFO_FILE, F_OK) == -1) { 
  17.         if ((mkfifo(FIFO_FILE, 0666) < 0) && (errno != EEXIST)) { 
  18.             printf("Filo file create error!\n"); 
  19.         } 
  20.     } 
  21.     pid_t newfork = fork(); 
  22.     if (newfork < 0) { 
  23.         printf("Fork error!\n"); 
  24.         exit(1); 
  25.     } else if (newfork == 0) { 
  26.         int fd1 = open(FIFO_FILE, O_RDONLY); 
  27.         int reader; 
  28.         if (fd1 < 0) { 
  29.             printf("child process fd error!\n"); 
  30.             exit(1); 
  31.         } 
  32.         while (1) { 
  33.             reader = read(fd1, buff, BUFFER_SIZE); 
  34.             if ((buff[0] == 'q' && buff[1] == '\0'
  35.                     || (buff[0] == 'Q' && buff[1] == '\0')) { 
  36.                 printf("Get EXIT message and quit!\n"); 
  37.                 close(fd1); 
  38.                 exit(0); 
  39.             } 
  40.             if (reader > 0) { 
  41.                 printf("Read from FIFO:%s\n", buff); 
  42.             } 
  43.         } 
  44.     } else { 
  45.         int fd2 = open(FIFO_FILE, O_WRONLY); 
  46.         int writer; 
  47.         if (fd2 < 0) { 
  48.             printf("Father process fd error!\n"); 
  49.             exit(1); 
  50.         } 
  51.         while (1) { 
  52.             if ((buff[0] == 'q' && buff[1] == '\0'
  53.                     || (buff[0] == 'Q' && buff[1] == '\0')) { 
  54.                 close(fd2); 
  55.                 exit(0); 
  56.             } 
  57.             scanf("%s", buff); 
  58.             writer = write(fd2, buff, BUFFER_SIZE); 
  59.         } 
  60.     }