Linux系統(tǒng)編程—有名管道
作者:良許Linux 
  管道,又名「無名管理」,或「匿名管道」,管道是一種非?;?,也是使用非常頻繁的IPC方式。
 一、管道的概念
管道,又名「無名管理」,或「匿名管道」,管道是一種非?;荆彩鞘褂梅浅nl繁的IPC方式。
1. 管道本質
- 管道的本質也是一種文件,不過是偽文件,實際上是一塊內核緩沖區(qū),大小4K;
 - 管道創(chuàng)建以后會產(chǎn)生兩個文件描述符,一個是讀端,另一個是寫端;
 - 管道里的數(shù)據(jù)只能從寫端被寫入,從讀端被讀出;
 
1. 管道原理
管道是內核的一塊緩沖區(qū),更具體一些,是一個環(huán)形隊列。數(shù)據(jù)從隊列的一端寫入數(shù)據(jù),另一端讀出,如下圖示:
3. 管道的優(yōu)點
簡單
4. 管道的缺點
- 只能單向通信,如果需要雙向通信則需要建立兩個管道;
 - 只能應用于具有血緣關系的進程,如父子進程;
 - 緩沖區(qū)大小受限,通常為1頁,即4k;
 
二、管道的創(chuàng)建
管道創(chuàng)建三步曲:
- 父進程調用pipe函數(shù)創(chuàng)建管道;
 - 父進程調用fork函數(shù)創(chuàng)建子進程;
 - 父進程關閉fd[0],子進程關閉fd[1];
 
具體如下圖所示:
三、管道的讀寫行為
- 管道的緩沖區(qū)大小固定為4k,所以如果管道內數(shù)據(jù)已經(jīng)寫滿,則無法再寫入數(shù)據(jù),進程的write調用將阻塞,直到有足夠的空間再寫入數(shù)據(jù);
 - 管道的讀動作比寫動作要快,數(shù)據(jù)一旦被讀走了,管道將釋放相應的空間,以便后續(xù)數(shù)據(jù)的寫入。當所有的數(shù)據(jù)都讀完之后,進程的read()調用將阻塞,直到有數(shù)據(jù)再次寫入。
 
四、例程
父子間通信:
- #include <stdio.h>
 - #include <sys/types.h>
 - #include <unistd.h>
 - #include <string.h>
 - int main()
 - {
 - int fd[2];
 - pid_t pid;
 - char buf[1024];
 - char *data = "hello world!";
 - /* 創(chuàng)建管道 */
 - if (pipe(fd) == -1) {
 - printf("ERROR: pipe create failed!\n");
 - return -1;
 - }
 - pid = fork();
 - if (pid == 0) {
 - /* 子進程 */
 - close(fd[1]); // 子進程讀取數(shù)據(jù),關閉寫端
 - read(fd[0], buf, sizeof(buf)); // 從管道讀數(shù)據(jù)
 - printf("child process read: %s\n", buf);
 - close(fd[0]);
 - } else if (pid > 0) {
 - /* 父進程 */
 - close(fd[0]); //父進程寫數(shù)據(jù),關閉讀端
 - write(fd[1], data, strlen(data)); // 向管道寫數(shù)據(jù)
 - printf("parent process write: %s\n", data);
 - close(fd[1]);
 - }
 - return 0;
 - }
 
兄弟間通信:
- #include <stdio.h>
 - #include <sys/types.h>
 - #include <unistd.h>
 - #include <string.h>
 - #include <sys/wait.h>
 - int main ()
 - {
 - int fd[2];
 - int i = 0;
 - pid_t pid;
 - char buf[1024];
 - char *data = "hello world!";
 - /* 創(chuàng)建管道 */
 - if (pipe(fd) == -1) {
 - printf("ERROR: pipe create failed!\n");
 - return -1;
 - }
 - for (i = 0; i < 2; i++) {
 - pid = fork();
 - if (pid == -1) {
 - printf("ERROR: fork error!\n");
 - return -1;
 - } else if (pid == 0) {
 - break;
 - }
 - }
 - /* 通過i來判斷創(chuàng)建的子進程及父進程 */
 - if (i == 0) {
 - /* 第一個子進程,兄進程 */
 - close(fd[0]); // 兄進程向弟進程寫數(shù)據(jù),關閉讀端
 - write(fd[1], data, strlen(data));
 - printf("elder brother send: %s\n", data);
 - close(fd[1]);
 - } else if (i == 1) {
 - /* 第二個子進程,弟進程 */
 - close(fd[1]);
 - read(fd[0], buf, sizeof(buf));
 - printf("younger brother receive: %s\n", buf);
 - close(fd[0]);
 - } else {
 - /* 父進程 */
 - close(fd[0]);
 - close(fd[1]);
 - for (i = 0; i < 2; i++) {
 - wait(NULL);
 - }
 - }
 - return 0;
 - }
 
本文授權轉載自公眾號「良許Linux」。良許,世界500強外企Linux開發(fā)工程師,公眾號里分享大量Linux干貨,歡迎關注!

責任編輯:趙寧寧 
                    來源:
                    今日頭條
 
















 
 
 


 
 
 
 