zoukankan      html  css  js  c++  java
  • linux socketpair

    相对于无名管道来说,socketpair也是使用在亲缘进程之间,不过它提供了能够全双工通信的通道

    man socketpair:

           #include <sys/types.h>          /* See NOTES */
           #include <sys/socket.h>
    
           int socketpair(int domain, int type, int protocol, int sv[2]);
    

      该sv保存的两个文件描述符,能写也能读

    #include <stdio.h>
    #include <errno.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <sys/socket.h>
    
    int main()
    {
        int sockfd[2] = {0};
    
        if (-1 == socketpair(PF_UNIX, SOCK_STREAM, 0, sockfd))
        {
            fprintf(stderr, "socketpair: %d, %s
    ", errno, strerror(errno));
            exit(1);
        }
    
        pid_t pid = fork();
    
        if (pid < 0)
        {
            fprintf(stderr, "fork: %d, %s
    ", errno, strerror(errno));
            exit(1);
        }
        if (pid == 0)
        {
            close(sockfd[1]);
            char buf[] = "data from child program";
            write(sockfd[0], buf, strlen(buf));
    
            char szRecv[200] = {0};
            read(sockfd[0], szRecv, 200);
            printf("in child program, get data: %s
    ", szRecv);
            
            close(sockfd[0]);
        }
        else
        {
            close(sockfd[0]);
    
            char szRecv[200] = {0};
            read(sockfd[1], szRecv, 200);
            printf("in parent program, get data: %s
    ", szRecv);
    
            char buf[] = "data from parent program";
            write(sockfd[1], buf, strlen(buf));
    
            close(sockfd[1]);
            wait(NULL);
        }
        
    	return 0;
    }
    

      

  • 相关阅读:
    length()
    matlab mod()&rem()
    tf调试函数
    64位win7+PCL1.6.0+VS2010,64位win10+PCL1.6.0+VS2010
    pcl 1.8 + VS 2010 在win7 x64下的配置
    Qt在vs2010下的配置
    VS2010 win7 QT4.8.0,实现VS2010编译调试Qt程序,QtCreator静态发布程序
    [POI2012]ROZ-Fibonacci Representation (贪心)
    CF 666C & 牛客 36D
    数位dp练习
  • 原文地址:https://www.cnblogs.com/zuofaqi/p/9608638.html
Copyright © 2011-2022 走看看