zl程序教程

您现在的位置是:首页 >  前端

当前栏目

socketpair函数_socket框架

框架 函数 socket socketpair
2023-06-13 09:14:33 时间

socketpair函数概要如下: #include <sys/types.h> 定义一些C宏常量 #include <sys/socket.h> 定义socketpair函数原型 int socketpair(int domain, int type, int protocol, int sv[2]);

socketpair函数需要四个参数: domain-套接口的域 type-套接口类型 protocol-使用的协议 sv[2]-指向存储文件描述符的指针

类型参数声明了我们希望创建哪种类型的套接口,socketpair函数的选择如下: SOCK_STREAM SOCK_DGRAM 对于socketpair函数,protocol参数必须提供为0。 参数sv[2]是接收代表两个套接口的整数数组。每一个文件描述符代表一个套接口,并且与另一个并没有区别。

如果函数成功,将会返回0值。否则将会返回-1表明创建失败,并且errno来表明特定的错误号。

socketpair可以用于多进程间全双工通讯。

1.调用socketpair,成功后便有两个socket文件描述符,一个socket就像是一个pipe。

在两个socket中指定一个给父进程使用,另外一个给子进程使用。不用在意指定哪一个socket给父进程使用,随便挑一个就可以了。

2.调用fork,成功后就创建了子进程

2.1 fork返回0,那就是子进程,关闭父进程的socket,保留子进程的socket

2.2 fork返回非0,那就是父进程,关闭子进程的socket,保留父进程的socket

为什么要关闭socket,现在还没有搞清楚。

3.现在有父子两个进程,每个进程都有一个socket描述符用以代表同一个pipe的两端。如果父进程调用write,那么子进程就调用read,反之亦然。

以下是一个代码示例片段:

void child(int socket) {
    const char hello[] = "hello parent, I am child";
    write(socket, hello, sizeof(hello)); /* NB. this includes nul */
    /* go forth and do childish things with this end of the pipe */
}

void parent(int socket) {
    /* do parental things with this end, like reading the child's message */
    char buf[1024];
    int n = read(socket, buf, sizeof(buf));
    printf("parent received '%.*s'\n", n, buf);
}

void socketfork() {
    int fd[2];
    static const int parentsocket = 0;
    static const int childsocket = 1;
    pid_t pid;

    /* 1. call socketpair ... */
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fd);

    /* 2. call fork ... */
    pid = fork();
    if (pid == 0) { /* 2.1 if fork returned zero, you are the child */
        close(fd[parentsocket]); /* Close the parent file descriptor */
        child(fd[childsocket]);
    } else { /* 2.2 ... you are the parent */
        close(fd[childsocket]); /* Close the child file descriptor */
        parent(fd[parentsocket]);
    }
    exit(0); /* do everything in the parent and child functions */
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/182106.html原文链接:https://javaforall.cn