Linux 程序間通訊 管道

2021-08-21 20:38:55 字數 1468 閱讀 8053

管道:

1.匿名管道

2.命名管道

我們下面看看匿名管道:

匿名管道注意的點:

1.匿名管道只能應用於具有親緣關係的兩個程序之間

2.管道提供流式服務

3.程序退出,管道釋放,管道的生命週期隨程序

4.核心會對管道操作進行同步與互斥

5.管道是半雙工的,資料只能向乙個方向流動,需要雙方通訊時,需要建立起兩個管道

命名管道:是一種特殊型別的檔案,可以是任意兩個程序之間通訊

可以在命令列中建立:

mkfifo filename

也可以在程式中建立:

int mkfifo(const char *filename,mode_t mode);

下面是建立命名管道,進行檔案的拷貝:

mkfifowrite.c

#include

#include

#include

#include

#include

#include

int main()

int outfd;

outfd = open("tp",o_wronly); //開啟管道

if(outfd == -1)

char buf[1024];

int n ;

while(( n = read(infd,buf,1024)) > 0) //進行寫管道

close(infd);

close(outfd);

return

0;}

mkfiforead.c

#include

#include

#include

#include

#include

#include

int main()

int infd;

infd = open("tp",o_rdonly); //開啟管道

if(infd == -1)

char buf[1024];

int n;

while((n = read(infd,buf,1024))> 0) //從管道中讀,寫到檔案中

close(infd);

close(outfd);

unlink("tp");

return

0;}

管道是半雙工的,在上面**執行中,當我只執行寫程式時,發現程式沒有結束。這時在另乙個視窗執行讀程式時,兩個程式同時結束。這充分說明了,管道中通訊兩方都必須是暢通的,否則管道使用失敗。

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傳送了資料...