zoukankan      html  css  js  c++  java
  • 管道的创建与读写-创建两个管道来实现一个全双工通信

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

    示例代码:

     

    #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
    ");
    
            read(fd1[0], bufc, sizeof(bufc));
            printf("child recv message:%s
    ", bufc);
            
    
            printf("child work finish
    ");
            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
    ");
    
            read(fd2[0], bufp, sizeof(bufp));
            printf("parent recv message:%s
    ", bufp);
    
            
            printf("parent work finish
    ");
            close(fd1[1]);
            close(fd2[0]);
    
            wait(NULL);//
    
            exit(0);
    
        }
        
    }
  • 相关阅读:
    维护win10注册表
    win10操作技巧
    无处不网络
    事件驱动编程思想
    流程控制之if...else
    python----GIL的概念
    并发与同步异步的概念
    实现并发join的方法
    线程的调用
    三元运算符
  • 原文地址:https://www.cnblogs.com/zhangxuan/p/6705184.html
Copyright © 2011-2022 走看看