歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 《Unix/Linux編程實踐教程》之管道

《Unix/Linux編程實踐教程》之管道

日期:2017/3/1 10:05:48   编辑:Linux編程

管道式內核中的一個單向的數據通道,用來連接一個進程的輸出和另一個進程的輸入。管道有一個讀取端和一個寫入端。

創建管道的系統調用為 pipe ,函數原型是 result=pipe(int array[2]); 調用 pipe 來創建管道並將其兩端連接到兩個文件描述符。 array[0] 為讀數據端的文件描述符, array[1] 是寫數據段端的文件描述符。

可以將 fork 和 pipe 結合起來寫個小程序, fork 出來的子進程每 5 秒向管道裡寫數據,父進程每 1 秒向管道裡寫數據,同時將管道裡現有的數據讀出來,輸出到 stdout 。

相關閱讀:

《Unix/Linux編程實踐教程》之Shell編程一 http://www.linuxidc.com/Linux/2012-12/75690.htm

《Unix/Linux編程實踐教程》之Shell編程二 http://www.linuxidc.com/Linux/2012-12/75691.htm

《Unix/Linux編程實踐教程》之管道 http://www.linuxidc.com/Linux/2012-12/75692.htm

Unix/Linux編程實踐教程【高清PDF中文版+附錄光盤+代碼】:http://www.linuxidc.com/Linux/2011-08/41374.htm

例子代碼如下:

1: /* pipedemo2.c* Demonstrates how pipe is duplicated in fork()

2:** Parent continues to write and read pipe,

3:*but child also writes to the pipe

4:*/

5: #include<stdio.h>

6:

7: #defineCHILD_MESS" I want a cookie/n "

8: #definePAR_MESS" testing../n "

9: #defineoops(m,x){ perror(m); exit (x); }

10:

11: main()

12: {

13: int pipefd[2];/* the pipe*/

14: int len;/* for write*/

15: char buf[BUFSIZ];/* for read*/

16: int read_len;

17:

18: if ( pipe( pipefd ) == -1 )

19: oops(" cannot get a pipe ", 1);

20:

21: switch ( fork() ){

22: case -1:

23: oops(" cannot fork ", 2);

24:

25: /* child writes to pipe every 5 seconds */

26: case 0:

27: len = strlen(CHILD_MESS);

28: while ( 1 ){

29: if ( write ( pipefd[1], CHILD_MESS, len) != len )

30: oops(" write ", 3);

31: sleep(5);

32: }

33:

34: /* parent reads from pipe and also writes to pipe */

35: default :

36: len = strlen( PAR_MESS );

37: while ( 1 ){

38: if ( write ( pipefd[1], PAR_MESS, len)!=len )

39: oops(" write ", 4);

40: sleep(1);

41: read_len = read ( pipefd[0], buf, BUFSIZ );

42: if ( read_len <= 0 )

43: break ;

44: write ( 1 , buf, read_len );

45: }

46: }

47: }

48:

需要注意的是:當進程試圖從管道讀數據時,進程被掛起直到數據被寫入管道。

Copyright © Linux教程網 All Rights Reserved