歡迎您光臨本站 註冊首頁

【Linux的那些事】關於FIFO

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0

最近在處理多進程間進行數據通信(基本上屬於1伺服器多客戶端類型的),而且通信的數據屬於視頻數據,量比較大,權衡再三,決定使用FIFO來處理.

伺服器與每個客戶端之間用一個專屬的FIFO有名管道,這就存在一個阻塞的問題,不過可以通過添加O_NONBLOCK來設置為非阻塞狀態.

下面是我寫的一個測試程序,包含客戶端和伺服器端,伺服器與每個客戶端之間單獨的fifo有名管道

客戶端:

  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <fcntl.h>
  8. #include <limits.h>
  9. #include <time.h>
  10. int main(int argc,char** argv){
  11. int fd;
  12. int len;
  13. char buf[PIPE_BUF];

  14. time_t tp;
  15. if(argc!=2){
  16. printf("Usage:client [Name]");
  17. }
  18. if((fd = open(argv[1],O_WRONLY))<0){
  19. perror("open");
  20. exit(EXIT_FAILURE);
  21. }
  22. while(1){
  23. time(&tp);
  24. len = sprintf(buf,"wrfifo: %d sends %s",getpid(),ctime(&tp));
  25. if((write(fd,buf,len 1))<0){
  26. perror("write");
  27. close(fd);
  28. exit(EXIT_FAILURE);
  29. }
  30. }
  31. close(fd);
  32. exit(EXIT_SUCCESS);
  33. }

伺服器端:

  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <fcntl.h>
  8. #include <limits.h>
  9. //#define PIPE_BUF 8192
  10. int main(void){
  11. int fd1,fd2;
  12. int dumy1,dumy2;
  13. int len1,len2;
  14. char buf1[PIPE_BUF],buf2[PIPE_BUF];
  15. mode_t mode = 0666;
  16. unlink("fifo1");
  17. unlink("fifo2");
  18. if((mkfifo("fifo1",mode))<0){
  19. perror("mkfifo1");
  20. exit(EXIT_FAILURE);
  21. }
  22. if((mkfifo("fifo2",mode))<0){
  23. perror("mkfifo2");
  24. exit(EXIT_FAILURE);
  25. }

  26. printf("open fifo1n");
  27. if((fd1=open("fifo1",O_RDONLY|O_NONBLOCK))<0){
  28. // if((fd1=open("fifo1",O_RDONLY,0))<0){
  29. perror("open1");
  30. exit(EXIT_FAILURE);
  31. }
  32. printf("open fifo2n");
  33. if((fd2=open("fifo2",O_RDONLY|O_NONBLOCK))<0){
  34. // if((fd2=open("fifo2",O_RDONLY,0))<0){
  35. perror("open2");
  36. exit(EXIT_FAILURE);
  37. }
  38. printf("loopn");
  39. while(1){
  40. len1 = read(fd1,buf1,PIPE_BUF-1);
  41. if(len1>0)
  42. printf("rdfifo1 read: %s",buf1);
  43. len2 = read(fd2,buf2,PIPE_BUF-1);
  44. if(len2>0)
  45. printf("rdfifo2 read: %s"

    ,buf2);
  46. }
  47. close(fd1);
  48. close(fd2);
  49. printf("exitn");
  50. exit(EXIT_SUCCESS);
  51. }

將上述程序編譯

分別在三個超級終端中運行 ./server ./client fifo1 ./client fifo2

如果把server.c裡面的open的參數中的O_NONBLOCK參數去掉,server的程序就會阻塞在第一個open操作中!

FIFO有一個缺點就是,管道名必須是伺服器端和客戶端協商好的.


[火星人 ] 【Linux的那些事】關於FIFO已經有463次圍觀

http://coctec.com/docs/linux/show-post-51977.html