Linux處理序間通訊之管道通訊

來源:互聯網
上載者:User

管道的一些特點如下:

它只能用於有親緣關係的進程之間的通訊(父子進程或兄弟進程)

它是一個半雙工的通訊模式,有固定讀端、寫端

管道可以看成一種特殊的檔案,讀寫可以使用普通的read、write等函數

 

1.管道建立

prototype : int pipi(int fd[2])

input : fd[2],管道的兩個檔案描述符,成功建立管道之後可以直接操作

output: 0 —— success

            -1 —— failure

 

例子:

#include <unistd.h><br />#include <errno.h><br />#include <stdio.h><br />#include <stdlib.h></p><p>int main(void)<br />{<br />int pipe_fd[2];</p><p>if (pipe(pipe_fd) < 0)<br />{<br />printf("pipe create error/n");<br />return -1;<br />}<br />else<br />{<br />printf("pipe create success/n");<br />}</p><p>close(pipe_fd[0]);<br />close(pipe_fd[1]);<br />}<br />

 

2.管道讀寫

建立管道之後,有兩個檔案描述符,分別是fd[0]和fd[1],其中fd[0]是讀取端,fd[1]是寫入端。以下例子中,子進程作為讀取端(需要關閉其寫入端),父進程作為寫入端(關閉其讀取端)。貼出代碼如下:

#include <unistd.h><br />#include <sys/types.h><br />#include <errno.h><br />#include <stdio.h><br />#include <stdlib.h></p><p>int main(void)<br />{<br />int pipe_fd[2];<br />pid_t pid;<br />char buf_r[100];<br />char* p_wbuf;<br />int r_num;</p><p>memset(buf_r, 0, sizeof(buf_r));</p><p>if (pipe(pipe_fd) < 0) //建立管道<br />{<br />printf("pipe create error/n");<br />return -1;<br />}</p><p>if ((pid = fork()) == 0) //進入子進程<br />{<br />printf("/n");<br />close(pipe_fd[1]); //關閉寫連接埠<br />sleep(2); //睡眠2s,等待父進程寫<br />if ((r_num = read(pipe_fd[0], buf_r, 100)) > 0)<br />{ //讀取管道內容<br />printf("%d numbers read from the pipe is %s/n", r_num, buf_r);<br />}<br />close(pipe_fd[0]); //關閉讀連接埠<br />exit(0);<br />}<br />else if (pid > 0) //進入父進程<br />{<br />close(pipe_fd[0]); //關閉讀連接埠<br />if (write(pipe_fd[1], "jarvis", 6) != -1)<br />{ //分兩次向管道寫入<br />printf("parent write_1 jarvis!/n");<br />}<br />if (write(pipe_fd[1], "hello", 5) != -1)<br />{<br />printf("parent write_2 hello!/n");<br />}<br />close(pipe_fd[1]);<br />sleep(3);<br />waitpid(pid, NULL, 0); //等待子進程結束<br />exit(0);<br />}<br />}<br />

編譯並運行,終端列印資訊如下:

 

OK,實現管道通訊!

 

聯繫我們

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