linux–管道pipe

來源:互聯網
上載者:User

在Linux中,管道是一種使用非常頻繁的通訊機制。從本質上說,管道也是一種檔案,但它又和一般的檔案有所不同,管道可以克服使用檔案進行通訊的兩個問題,具體表現為:

  · 限制管道的大小。實際上,管道是一個固定大小的緩衝區。在Linux中,該緩衝區的大小為1頁,即4K位元組,使得它的大小不象檔案那樣不加檢驗地增長。使用單個固定緩衝區也會帶來問題,比如在寫管道時可能變滿,當這種情況發生時,隨後對管道的write()調用將預設地被阻塞,等待某些資料被讀取,以便騰出足夠的空間供write()調用寫。

  · 讀取進程也可能工作得比寫進程快。當所有當前進程資料已被讀取時,管道變空。當這種情況發生時,一個隨後的read()調用將預設地被阻塞,等待某些資料被寫入,這解決了read()調用返迴文件結束的問題。

  注意:從管道讀資料是一次性操作,資料一旦被讀,它就從管道中被拋棄,釋放空間以便寫更多的資料

#include<stdio.h>

 #include<unistd.h> 

#include<sys/types.h>

 int main(void) 

{

intfd[2],nbytes; pid_tchildpid; 

charstring[]="Hello,world!\n"; 

charreadbuffer[80]; pipe(fd);

 if((childpid=fork())==-1) { perror("fork"); exit(1); } 

if(childpid==0) { /*Child process closes up in put side of pipe*/ close(fd[0]); /*Send"string"through the out put side of pipe*/

 write(fd[1],string,strlen(string)); 

exit(0); }

 else { 

/*Parent process closes up out put side of pipe*/ close(fd[1]); 

/*Readinastringfromthepipe*/ nbytes=read(fd[0],readbuffer,sizeof(readbuffer)); 

printf("Receivedstring:%s",readbuffer); }

 return(0);

 }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.