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;
    }
    

      

  • 相关阅读:
    ==与is区别
    词典操作
    前端工具---取色截图测量
    css零碎合集
    基于bootstrap的在线布局工具
    js常用功能工具库--Underscore.js
    前端资源荟萃
    在线绘图工具---processon
    表单form浅谈
    前端工具----iconfont
  • 原文地址:https://www.cnblogs.com/zuofaqi/p/9608638.html
Copyright © 2011-2022 走看看