zoukankan      html  css  js  c++  java
  • linux的套接口和管道

      创建管道的函数:

    #include <unistd.h>
    int pipe(int pipefd[2]);

      pipefd[0]代表管道读出端的文件描述符,pipefd[1]代表管道写入端的文件描述符。信息只能从pipefd[0]读出,也只能重pipefd[1]写进。所以实现的通信就是单项的,如果要实现双向通信的话可以采用建立两个管道。不过也可以使用套接字通信。因为套接字的通信是双向的。

      创建管道的例子:

    #include <sys/wait.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    int
    main(int argc, char *argv[])
    {
        int pipefd[2];
        pid_t cpid;
        char buf;
        if (argc != 2) {
          fprintf(stderr, "Usage: %s <string>\n", argv[0]);
          exit(EXIT_FAILURE);
        }
        if (pipe(pipefd) == -1) {
            perror("pipe");
            exit(EXIT_FAILURE);
        }
        cpid = fork();
        if (cpid == -1) {
            perror("fork");
            exit(EXIT_FAILURE);
        }
        if (cpid == 0) {    /* 子进程从管道中读取 */   
            close(pipefd[1]);          /* 读的时候先关闭不用的写进端 */
            while (read(pipefd[0], &buf, 1) > 0)
                write(STDOUT_FILENO, &buf, 1);
            write(STDOUT_FILENO, "\n", 1);
            close(pipefd[0]);
            _exit(EXIT_SUCCESS);
        } else {            /* 父进程向管道写入 argv[1]*/
            close(pipefd[0]);          /* 写之前关闭不用的读出端*/
            write(pipefd[1], argv[1], strlen(argv[1]));
            close(pipefd[1]);          /* Reader will see EOF */
            wait(NULL);                /* Wait for child */
            exit(EXIT_SUCCESS);
        }
    }

      

      创建套接口的函数:

    #include <sys/types.h> 
    #include <sys/socket.h>
    int socketpair(int domain, int type, int protocolint " sv [2]);

      sv[2]是指向接收用于引用套接口文件描述符数组的指针。类似于管道中的端点。使用例子:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <errno.h>
    #include <string.h>#include <sys/types.h>
    #include <sys/socket.h>
    
    int main()
    {
        int z;
        int s[2];
        
        z = socketpair(AF_LOCAL,SOCK_STREAM,0,s);
        if (z==-1)
        {
            fprintf(stderr,"%s:socketpair(AF_LOCAL,SOCK_STREAM,0)\n",strerror(errno));
            exit(1);
        }
    
        printf("s[0]=%d;\n",s[0]);
        printf("s[1]=%d;\n",s[1]);
        return 1;    
    }

       下一篇:套接口和I/O通信

    作者:涵曦www.hanxi.cc
    出处:hanxi.cnblogs.com
    GitHub:github.com/hanxi
    Email:im.hanxi@gmail.com
    文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

    《 Skynet 游戏服务器开发实战》

  • 相关阅读:
    读书书单
    Kafka学习-Producer和Customer
    Kafka学习-简介
    Maven学习-Profile详解
    Maven学习-项目对象模型
    Maven学习-优化和重构POM
    Maven学习-构建项目
    Maven学习-简介、安装
    连接web端,mysql,返回乱码解决
    android alipay
  • 原文地址:https://www.cnblogs.com/hanxi/p/2533861.html
Copyright © 2011-2022 走看看