管道:是指用於連接一個讀進程和一個寫進程,以實現它們之間通信的共享文件,又稱pipe文件。
管道是單向的、先進先出的、無結構的、固定大小的字節流,它把一個進程的標准輸出和另一個進程的標准輸入連接在一起。
寫進程在管道的尾端寫入數據,讀進程在管道的首端讀出數據。
數據讀出后將從管道中移走,其它讀進程都不能再讀到這些數據。
管道提供了簡單的流控制機制。進程試圖讀空管道時,在有數據寫入管道前,進程將一直阻塞。同樣,管道已經滿時,進程再試圖寫管道,在其它進程從管道中移走數據之前,寫進程將一直阻塞。
匿名管道
匿名管道:進程試圖讀空管道時,在有數據寫入管道前,進程將一直阻塞。同樣,管道已經滿時,進程再試圖寫管道,在其它進程從管道中移走數據之前,寫進程將一直阻塞。在系統中沒有實名,不能在文件系統中以任何方式看到該管道,它只是進程的一種資源,會隨着進程的結束而被系統清除只能用於具有親緣關系的進程之間,如父子進程或兄弟進程之間
例子:寫一程序 父進程創建子進程,並向子進程通過匿名管道傳送信息hello,子進程接收到信息向父進程傳送hi
#include<unistd.h> #include<stdio.h> #include<stdlib.h> #define BUFSZ 256 int main(void) { int fd[2]; char buf[BUFSZ]; pid_t pid; int len; if( pipe(fd)<0 ) { perror("failed to pipe"); exit(1); } if( (pid = fork())<0 ) { perror("failed to fork"); exit(1); } else if(pid > 0) { printf("This is farther, write hello to pipe\n"); write(fd[1], "hello\n", 25); sleep(1); read(fd[0], buf, BUFSZ); printf("father read result is %s\n", buf); exit(0); } else { printf("This is child ,read from pipe\n"); read(fd[0], buf, BUFSZ); printf("child read result is %s\n", buf); printf("This is child, write reply to pipe\n"); write(fd[1], "hi\n", 50); } return 0; }
運行結果: