socketpair--父子进程交互
  llt0tXqeaug8 2023年12月02日 32 0


在C语言中,socketpair 函数的原型通常是:

#include <sys/types.h>
#include <sys/socket.h>


int socketpair(int domain, int type, int protocol, int sv[2]);

其中:


  • domain 参数指定了地址族(address family),通常为 AF_UNIX,表示使用 UNIX 域套接字。

  • type 参数指定了套接字的类型,通常为 SOCK_STREAM(字节流套接字)或 SOCK_DGRAM(数据报套接字)。

  • protocol 参数指定了具体的协议,通常为 0,表示使用默认协议。

  • sv 参数是一个用于存储创建的套接字描述符的数组。在成功时,sv[0] 和 sv[1] 分别是这对相互连接的套接字的描述符。


下面是一个简单的例子,演示了如何使用 socketpair 在父子进程之间传递数据:

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>


int main() {
    int sv[2];


    if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) {
        perror("socketpair");
        return 1;
    }


    pid_t pid = fork();


    if (pid == -1) {
        perror("fork");
        return 1;
    }


    if (pid == 0) { // Child process
        close(sv[0]);  // Close the parent side of the socket


        const char *message = "Hello from the child!";
        write(sv[1], message, strlen(message));


        close(sv[1]);
    } else { // Parent process
        close(sv[1]);  // Close the child side of the socket


        char buffer[100];
        ssize_t bytesRead = read(sv[0], buffer, sizeof(buffer));


        if (bytesRead == -1) {
            perror("read");
            return 1;
        }


        buffer[bytesRead] = '\0';
        printf("Received from child: %s\n", buffer);


        close(sv[0]);
    }


    return 0;
}



【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月02日 0

暂无评论

推荐阅读
  gBkHYLY8jvYd   2023年12月06日   48   0   0 #includecii++
  gBkHYLY8jvYd   2023年11月19日   27   0   0 #includecic++
  gBkHYLY8jvYd   2023年11月19日   14   0   0 #includeios数据
  gBkHYLY8jvYd   2023年11月19日   20   0   0 #includei++数据
  gBkHYLY8jvYd   2023年11月19日   23   0   0 #include数组ci
  gBkHYLY8jvYd   2023年12月10日   17   0   0 #include邻域灰度图像
  gBkHYLY8jvYd   2023年12月10日   22   0   0 #include数组i++
  gBkHYLY8jvYd   2023年12月06日   19   0   0 #includeios数据
  gBkHYLY8jvYd   2023年12月08日   20   0   0 #includecii++
  gBkHYLY8jvYd   2023年11月19日   19   0   0 #includeiosci
  gBkHYLY8jvYd   2023年11月22日   20   0   0 #include十进制高精度
  gBkHYLY8jvYd   2023年11月22日   23   0   0 #includeiosci
llt0tXqeaug8