管道读写

管道对于写入其中的数据A具有保护措施,当数据A没有读出的时候,再次向管道输送数据B ,此时数据B不会覆盖数据A,当读操作来临时,会把数据A和B按顺序读出。
#include <stdio.h>
#define CHILD_MESS "I am the first message/n"
#define PAR_MESS   "I am the second message./n"
int main()
{
    int pipefd[2];
    int len;
    char buf[BUFSIZ];
    int read_len;
    if(pipe(pipefd)==-1)
    {
        perror("fork");
        exit(1);
    }
    
    if(write(pipefd[1],CHILD_MESS,strlen(CHILD_MESS))!=strlen(CHILD_MESS))
    {
        perror("writing to pipe");
        exit(2);
    }
    if(write(pipefd[1],PAR_MESS,strlen(PAR_MESS))!=strlen(PAR_MESS))
    {
        perror("witing to pipe again befor the pre-one being read");
        exit(3);
    }
    if((read_len=read(pipefd[0],buf,BUFSIZ))==-1)
    {
        perror("read pipe");
        exit(4);
    }
    
    if(write(1,buf,read_len)!=read_len)
    {
        perror("write to stdout");
        exit(5);
    }
return 0;
}

输出结果:
[fxp@localhost ~]$ ./a.out
I am the first message
I am the second message.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值