pipe system call(原创)

王朝other·作者佚名  2006-01-31
窄屏简体版  字體: |||超大  

使用unix的时候,比如说在C shell上输入[last|more -10],就会从[more -10]的输入给出[last]的输出结果。unix这样的机能就叫做pipe。

为了实现pipe,先用pipe system call做出pipe用的file descriptor(文件描述符)。为了解释pipe system call的用法,给出了以下的简单program:

1 #include <stdio.h>

2

3 #define BSIZE 512

4 char send_buf[]="Computer Science";

5

6 main(){

7 int p_fd[2],n_send,n_recv;

8 char recv_buf[BSIZE];

9

10 pipe(p_fd);

11

12 n_send = strlen(send_buf)+1;

13 write(p_fd[1],send_buf,n_send);

14 close(p_fd[1]);

15

16 n_recv = read(p_fd[0],recv_buf,BSIZE);

17 close(p_fd[0]);

18

19 printf("%d bytes sent, %d bytes recieved.\n",n_send,n_recv);

20 printf("recieved data: %s\n",recv_buf);

21

22 exit(0);

23 }

pipe system call取一个参数,用这个参数指定由有2个整数型要素的数列。10行把数列p_fd作为参数呼出pipe system call。pipe system call成功的话,返回值返回0,在p_fd[0]里存入输入侧的file descriptor,p_fd[1]存入输出侧的file descriptor。

在13行的pipe的输出侧输出Computer Science。(15行的strlen函数是求文字列的文字数的库函数。)然后,输出结束的file descriptor p_fd[1]变得不再需要了消除。

在16行,从pipe的输入侧对recv_buf进行输入。结束之后像上面一样file descriptor p_fd[0]不再需要,消除。

最后表示出 pipe输出侧的输出文字数,从pipe输入侧输入的文字数(都是17bit)。然后表示输入用buf的recv_buf的内容,确定通过pipe把Computer Science这个数据正确的传输了。

结果如下:

$ ./a.out

17 bytes sent, 17 bytes recieved.

recieved data: Computer Science

(以上文章的版权在fastso,转载时请与本人取得联系,谢谢!)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航