函數說明:創建一個命名管道,如果成功則返回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,那麼只寫打開將出錯返回,其errno是ENXIO
- //readfifo.cc
- #include <iostream>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- using namespace std;
- const char *fifo_path = "/home/hahaya/Program/進程間通信之命名管道/fifo";
- int main()
- {
- //創建一個命名管道
- int ret = mkfifo(fifo_path, O_CREAT|0777);
- if(ret == -1)
- {
- cout << "create fifo failed..." << endl;
- return 0;
- }
- //打開命名管道
- int fd = open(fifo_path, O_RDONLY|O_NONBLOCK);
- if(fd == -1)
- {
- cout << "open fifo failed..." << endl;
- return 0;
- }
- //從管道中讀取數據
- char buff[128] = {'\0'};
- while(1)
- {
- if(read(fd, buff, sizeof(buff)) > 0)
- {
- cout << buff << endl;
- }
- }
- //關閉命名管道
- close(fd);
- return 0;
- }
- //writefifo.cc
- #include <iostream>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- using namespace std;
- const char *fifo_path = "/home/hahaya/Program/進程間通信之命名管道/fifo";
- int main()
- {
- //打開命名管道
- int fd = open(fifo_path, O_WRONLY|O_NONBLOCK, 0);
- if(fd == -1)
- {
- cout << "open fifo failed..." << endl;
- return 0;
- }
- //向管道中寫入數據
- char buff[128] = {'\0'};
- while(1)
- {
- cin.getline(buff, sizeof(buff));
- write(fd, buff, sizeof(buff));
- }
- close(fd);
- return 0;
- }
1 先運行readfifo程序再運行writefifo,因爲命名管道fifo是再readfifo程序中創建的
2 需要確保fifo_path下沒有fifo這個文件,否則在運行readfifo程序時因爲命名管道fifo已存在,所以執行mkfifo函數會失敗,則會直接退出readfifo程序
3 在writefifo程序下輸入的字符,會再readfifo程序下顯示