《Unix/Linux编程实践教程》之管道


管道式内核中的一个单向的数据通道,用来连接一个进程的输出和另一个进程的输入。管道有一个读取端和一个写入端。

创建管道的系统调用为 pipe ,函数原型是 result=pipe(int array[2]); 调用 pipe 来创建管道并将其两端连接到两个文件描述符。 array[0] 为读数据端的文件描述符, array[1] 是写数据段端的文件描述符。

可以将 fork 和 pipe 结合起来写个小程序, fork 出来的子进程每 5 秒向管道里写数据,父进程每 1 秒向管道里写数据,同时将管道里现有的数据读出来,输出到 stdout 。

《Unix/Linux编程实践教程》之Shell编程一

《Unix/Linux编程实践教程》之Shell编程二

《Unix/Linux编程实践教程》之管道

Unix/Linux编程实践教程【高清PDF中文版+附录光盘+代码】:

例子代码如下:

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:

需要注意的是:当进程试图从管道读数据时,进程被挂起直到数据被写入管道。

相关内容

    暂无相关文章