管道和FIFO

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

  1. 管道(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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.