管道的创建与读写-创建两个管道来实现一个全双工通信

管道是半双工的(一端只能读不能写,一端只能写不能读),但是可以通过创建两个管道来实现一个全双工(两端都可以读写)通信。

示例代码:

 

#include <stdio.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h>



int main()
{
    char* strc = "from parent's message";
    char* strp = "from child's message";
    char bufc[30];
    char bufp[30];
    bzero(bufc, sizeof(bufc));
    bzero(bufp, sizeof(bufp));
    pid_t pid;
    int fd1[2];
    int fd2[2];

    pipe(fd1);
    pipe(fd2);

    pid = fork();
    if(0 == pid)//child read
    {

        close(fd1[1]);
        close(fd2[0]);

        write(fd2[1], strp, strlen(strp)+1);
        printf("child write work finish\n");

        read(fd1[0], bufc, sizeof(bufc));
        printf("child recv message:%s\n", bufc);
        

        printf("child work finish\n");
        close(fd1[0]);
        close(fd2[1]);
        
        exit(0);
        

    }
    else//parent write
    {

        close(fd1[0]);
        close(fd2[1]);
        
        write(fd1[1], strc, strlen(strc)+1);
        printf("parent write work finish\n");

        read(fd2[0], bufp, sizeof(bufp));
        printf("parent recv message:%s\n", bufp);

        
        printf("parent work finish\n");
        close(fd1[1]);
        close(fd2[0]);

        wait(NULL);//

        exit(0);

    }
    
}

 

转载于:https://www.cnblogs.com/zhangxuan/p/6705184.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值