進程間通信---命名管道

函數原型:int mkfifo(const char *pathname, mode_t mode);

函數說明:創建一個命名管道,如果成功則返回0,,否則返回-1

 

函數原型:int open(const char *pathname, int flag);

函數說明:一旦已經用mkfifo創建了一個命名管道,就可以用open打開它。返回-1則打開管道失敗

 

函數原型:int close(int fd);

函數說明:可以用來關閉一個創建了的管道

 

當打開一個FIFO(命名管道時),非阻塞標誌(O_NONBLOCK)產生下列影響:

(1) 在一般情況中(沒有說明O_NONBLOCK),只讀打開要阻塞到某個其他進程爲寫打開此FIFO。同理,爲寫而打開一個FIFO要阻塞到某個其他進程爲讀而打開它

(2) 如果指定了O_NONBLOCK,則只讀打開立即返回。但是,如果沒有進程爲讀而打開一個FOFO,那麼只寫打開將出錯返回,其errnoENXIO

 

  1. //readfifo.cc  
  2. #include <iostream>  
  3. #include <sys/types.h>  
  4. #include <sys/stat.h>  
  5. #include <fcntl.h>  
  6. using namespace std;  
  7.   
  8. const char *fifo_path = "/home/hahaya/Program/進程間通信之命名管道/fifo";  
  9.   
  10. int main()  
  11. {  
  12.     //創建一個命名管道  
  13.     int ret = mkfifo(fifo_path, O_CREAT|0777);  
  14.     if(ret == -1)  
  15.     {  
  16.     cout << "create fifo failed..." << endl;  
  17.     return 0;  
  18.     }  
  19.   
  20.     //打開命名管道  
  21.     int fd = open(fifo_path, O_RDONLY|O_NONBLOCK);  
  22.     if(fd == -1)  
  23.     {  
  24.     cout << "open fifo failed..." << endl;  
  25.     return 0;  
  26.     }  
  27.   
  28.     //從管道中讀取數據  
  29.     char buff[128] = {'\0'};  
  30.     while(1)  
  31.     {  
  32.     if(read(fd, buff, sizeof(buff)) > 0)  
  33.     {  
  34.         cout << buff << endl;  
  35.     }  
  36.     }  
  37.   
  38.     //關閉命名管道  
  39.     close(fd);  
  40.     return 0;  
  41. }  
  42.   
  43.   
  44. //writefifo.cc  
  45. #include <iostream>  
  46. #include <sys/types.h>  
  47. #include <sys/stat.h>  
  48. #include <fcntl.h>  
  49. using namespace std;  
  50.   
  51. const char *fifo_path = "/home/hahaya/Program/進程間通信之命名管道/fifo";  
  52.   
  53. int main()  
  54. {  
  55.     //打開命名管道  
  56.     int fd = open(fifo_path, O_WRONLY|O_NONBLOCK, 0);  
  57.     if(fd == -1)  
  58.     {  
  59.     cout << "open fifo failed..." << endl;  
  60.     return 0;  
  61.     }  
  62.   
  63.     //向管道中寫入數據  
  64.     char buff[128] = {'\0'};  
  65.     while(1)  
  66.     {  
  67.     cin.getline(buff, sizeof(buff));  
  68.     write(fd, buff, sizeof(buff));  
  69.     }  
  70.   
  71.     close(fd);  
  72.     return 0;  
  73. }  

先運行readfifo程序再運行writefifo,因爲命名管道fifo是再readfifo程序中創建的

需要確保fifo_path下沒有fifo這個文件,否則在運行readfifo程序時因爲命名管道fifo已存在,所以執行mkfifo函數會失敗,則會直接退出readfifo程序

writefifo程序下輸入的字符,會再readfifo程序下顯示


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章