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);
    
        }
        
    }
  • 相关阅读:
    闭包和this
    闭包与变量
    闭包
    ES6扩展运算符的几个小技巧
    js对象的深拷贝
    js获取当前点击元素的索引
    前端学习指北
    css实现心形图案
    this 知多少
    js数字进制转换
  • 原文地址:https://www.cnblogs.com/zhangxuan/p/6705184.html
Copyright © 2011-2022 走看看