pipe system call(原创)

本文介绍了Unix的pipe机能,即在C shell上输入特定命令可从指定输入给出输出结果。为实现pipe,使用pipe system call创建文件描述符,并给出简单C程序示例。程序通过pipe system call获取输入输出侧文件描述符,完成数据传输,最后验证了数据传输的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用unix的时候,比如说在C shell上输入[lastmore -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 callpipe system call成功的话,返回值返回0,在p_fd[0]里存入输入侧的file descriptorp_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)。然后表示输入用bufrecv_buf的内容,确定通过pipeComputer Science这个数据正确的传输了。

 

结果如下:

 

$ ./a.out

 

17 bytes sent, 17 bytes recieved.

 

recieved data: Computer Science

 

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值