標籤:style blog http io ar color os 使用 sp
- 管道(pipe)
管道在Unix及Linux處理序間通訊是最基礎的,很容易理解。管道就像一個自來水管,一端注入水,一端放出水,水只能在一個方向上流動,而不能雙向流動。管道是典型的單向通訊,即電腦網路中所說的“半雙工”。管道又名匿名管道,所以只能用在具有公用祖先的進程之間使用,通常使用在父子進程之間通訊。通常是父進程建立一個管道,然後fork一個子進程,此後父子進程共用這個管道進行通訊。 管道由pipe函數建立,函數原型如下: #include<unistd.h> int pipe(int fd[2]); 成功返回0,否則返回-1;參數fd返回兩個檔案描述符,fd[0]為讀,fd[1]為寫,fd[1]的輸入是fd[0]的輸出。即fd[0]對應讀端,fd[1]對應寫端。 舉例說明一下管道的用法:類比client-server通訊過程,父進程類比client,子進程類比server。server向client發送一個字串,client接收到輸出到螢幕。
1 #include <unistd.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <sys/types.h> 5 #include <errno.h> 6 #include <string.h> 7 8 int main() 9 {10 int fd[2];11 pid_t childpid;12 char buf[100];13 14 memset(buf,0,100);15 //建立一個管道16 if(pipe(fd) == -1)17 {18 perror("pipe() error");19 exit(-1);20 }21 //建立一個子進程22 childpid = fork();23 if(childpid == 0)24 {25 printf("server input a message : ");26 scanf("%s",buf);27 //關閉讀端28 close(fd[0]);29 write(fd[1],buf,strlen(buf));30 exit(0);31 }32 if(childpid == -1)33 {34 perror("fork() error");35 exit(-1);36 }37 //父進程關閉寫端38 close(fd[1]);39 read(fd[0],buf,100);40 printf("client read a message: %s\n",buf);41 waitpid(childpid,NULL,0);42 return 0;43 }複製代碼View Code
管道和FIFO