程序間通訊(IPC) 管道(Pipe)

2021-06-12 10:42:02 字數 1345 閱讀 9078

管道:乙個程序連線資料流到另乙個程式

pipe函式的原型:

#include int pipe(int file_descriptor[2]);
該閃身在陣列中填上兩個新的檔案描述符後返回0,如果失敗則返回-1。寫到file_descriptor[1]的所有資料都可以從file_descriptor[0]讀回來。這裡使用的是檔案描述符而不是檔案流,所以我們必須用底層的read和write呼叫來訪問資料,而不是用檔案流庫函式fread和fwrite

#include #include #include #include int main()

exit(exit_failure);

}~

輸出:

wrote 3 bytes

read 3 bytes: 123

可以通過管道在兩個程序之間傳遞資料

#include #include #include #include int main()

// we've made sure the fork worked, so if fork_result equals zero, we're in the child process.

if (fork_result == 0)

// otherwise, we must be the parent process.

else

}exit(exit_success);

}

輸出:

wrote 3 bytes

jessica@ubuntu:~$ read 3 bytes: 123

這個程式實現了再不同的程序之間進行讀寫操作。但僅僅是執行乙個相同的程式。

接下來的程式中子程序中執行乙個與其父程序完全不同的另外乙個程式。

下面是pipe3.c

#include #include #include #include int main()

if (fork_result == 0)

else

}exit(exit_success);

}

下面試pipe4.c

#include #include #include #include int main(int argc, char *argv)

pipe3在程式中呼叫pipe4,pipe4程式從引數字串中提取出檔案描述符數字,然後讀取該檔案描述符來獲取資料。

程序間的通訊IPC 匿名管道pipe

管道 實現原理 核心借助環形佇列機制,使用核心緩衝區實現。特質 1.偽檔案 不占用磁碟空間 2.管道中的資料只能一次讀取。3.資料在管道中,只能單向流動。侷限性 1.自己寫,不能自己讀。不能同時進行讀寫操作 2.資料不可以反覆讀。3.雙向半雙工通訊。可以讀也可以寫,但同一程序只能是其中的一種 4.血...

程序間通訊 IPC 管道

管道是unix ipc最古老的形式,所有unix系統都提供此通訊機制。管道的兩種限制 1 半雙工,資料單方向流動。2只能用於具有公共祖先的程序之間。需要雙方通訊時,需要建立起兩個管道。例外 流管道沒有限制1,fifo和命名管道沒有限制2。管道是乙個檔案,但它不屬於某種檔案系統,而是 單獨構成一種檔案...

程序間通訊(IPC) 管道

二 fifo 命名管道 參考管道是一種最基本的ipc機制,作用於有血緣關係的程序之間,完成資料傳遞,呼叫pipe系統函式即可建立乙個管理。有如下性質 1.其本質是乙個偽檔案 實為核心緩衝區 所謂的偽檔案是指不佔磁碟空間大小的檔案,linux的檔案除了 l d,其它的s,b,c,p等都是偽檔案。2.由...