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

示例代码:

 

#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);

    }
    
}

 

posted on 2017-04-13 17:56  邶风  阅读(1453)  评论(0编辑  收藏  举报