pipe函式原型
標頭檔案:
int pipe(int file_descriptor[2]);
功 能:建立一無名管道
參 數:file_descriptor:檔案描述符陣列,其中file_descriptor[0]表示讀端,file_descriptor[1]表示寫端
返回值:成功返回0,失敗返回-1
開闢了管道之後如何實現兩個程序間的通訊呢?比如可以按下面的步驟通訊。
1、父程序呼叫pipe開闢管道,得到兩個檔案描述符指向管道的兩端。
2、父程序呼叫fork建立子程序,那麼子程序也有兩個檔案描述符指向同一管道。
3、父程序關閉管道讀端,子程序關閉管道寫端。父程序可以往管道裡寫,子程序可以從
4、管道裡讀,管道是用環形佇列實現的,資料從寫端流入從讀端流出,這樣就實現了程序間通訊。
執行結果#include #include #define maxline 80
int main(void)
if ((pid = fork()) < 0)
if (pid > 0) // 父程序
else //子程序
return 0;
}
注意事項
pipe是有血緣關係程序之間的通訊,那麼當沒有血緣關係的程序想要通訊怎麼辦?
與匿名管道pipe的區別
如何建立fifo?
做個測試,分別寫兩個程式,乙個寫,乙個讀
寫程序
讀程序#include #include #include #include #include #include #include int main(int argc, char* ar**)
fd = open(ar**[1], o_wronly);//只寫方式開啟
if (fd < 0)
write(fd, buff, strlen(buff));//寫入hello world
close(fd);
return 0;
}
測試結果如下#include #include #include #include #include #include #include int main(int argc, char* ar**)
fd = open(ar**[1], o_rdonly);//只寫方式開啟
if (fd < 0)
len = read(fd, buff, sizeof(buff));
write(stdout_fileno, buff, len);
close(fd);
return 0;
}
首先myfifo是我們提前建立好的fifo管道檔案,然後執行寫程序,再執行讀程序。讀到了hello world,執行前後myfifo檔案大小都為0
程序間通訊也可以通過記憶體共享對映或者socket進行通訊,之後會專門進行詳細解釋
Linux程序間通訊 管道
linux程序間通訊機制 1.同一主機程序間通訊機制 unix方式 有名管道fifo 無名管道pipe 訊號signal systemv方式 訊號量 訊息佇列 共享記憶體 2.網路通訊 rpc remote procedure call socket 管道管道是程序間通訊中最古老的方式,它包括無名管...
Linux程序間通訊 管道
管道 管道是一種最基本的程序間通訊機制,由pipe函式建立 include intpipe int filedes 2 呼叫pipe函式時在核心中開闢一塊緩衝區 稱為管道 用於通訊,它有乙個讀端乙個寫端,然後通過filedes引數傳出給使用者程式兩個檔案描述符,filedes 0 指向管道的讀端,f...
Linux 程序間通訊 管道
程序間通訊 a程序怎樣將 hello world 傳遞給b程序 i 利用檔案實現 需要乙個 中間人 進行傳遞 檔案 在磁碟中儲存 a先呼叫open函式開啟檔案,再用write函式寫檔案,b用read函式讀取檔案,但問題如下 1.如果a傳送了資料b進行了接收,但a的資料沒有被清空 2.如果a傳送了資料...