多個程序讀寫pipe
阿新 • • 發佈:2019-01-03
#include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #include<iostream> #include<wait.h> #include<stdlib.h> #include<memory.h> using namespace std; int main() { int fifofd = mkfifo("./bbb", S_IRUSR|S_IWUSR); cout<<"fifofd:"<<fifofd<<endl; if(fork()) {int fd3 = open("./bbb", O_RDONLY); -------------------------------> #1 int fd4 = open("./bbb", O_RDONLY); -------------------------------> #1 sleep(10); char buf[100]; memset(buf, 0, 100); cout<<"read size:"<<read(fd3, buf, 4)<<endl;----------------------》#2 cout<<buf<<endl; memset(buf, 0, 100); cout<<"read size:"<<read(fd4, buf, 4)<<endl;----------------------》#2 cout<<buf<<endl; exit(0); }else{ int fd1 = open("./bbb", O_WRONLY); --------------------------------> #1 int fd2 = open("./bbb", O_WRONLY); --------------------------------> #1 write(fd1, "fd1", 4); ---------------------------------------------》#2 write(fd2, "fd2", 4);----------------<span style="font-family: Arial, Helvetica, sans-serif;">---------------------------------------------》#2</span> } int status; wait(&status); }
結果:
fifofd:-1
read size:4
fd1
read size:4
fd2
注:
如果第一個讀端讀取8個位元組,則輸出如下:
fifofd:-1
read size:8
<span style="color:#ff6600;">fd1</span>
read size:0
說明: #1: 有名管道的讀與寫端的開啟必須成對,意思是當寫端或讀端開啟時,會暫時阻塞, 等待另一端開啟再執行。
#2: 多個寫程序可以寫一個pipe,(內容邏輯上是分隔的),讀時即便讀了多個寫程序的資料,有效的仍是第一個寫程序的資料,
如何知道每個寫程序寫了多少資料,再分別用每個讀程序按每個寫程序寫入的資料量來讀取,則會正確的讀到資料。