【博客323】使用socketpair进行通信

    技术2024-07-07  86

    内容: 通信的另一种方式:socketpair

    使用方法:

    1、socketpair是一种双向通讯机制,它通过socket实现双向通讯。 2、socketpair使用场景: * 在一个进程的线程之间进行双向通讯 * 在具有亲缘关系的进程间进行通讯

    实例:

    在main线程创建出新的线程,此时main线程和子线程同属一个进程,它们之间使用socketpair进行通信

    代码:

    #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> static void *thread_run_func (void *arg) { int thread_fd = (int)arg; char thread_buf[50] = {0}; int readlen; /* 向主进程发送一个消息 */ printf("send to main thread : %s\n", "Hello,main!"); write(thread_fd, "Hello,main!", sizeof("Hello,main!")); /* 接收主进程发送的消息 */ readlen = read(thread_fd, thread_buf, 50); thread_buf[readlen] = '\0'; printf("recv from main thread : %s\n", thread_buf); } int main(int argc, char *argv[]) { int sockets[2]; int result; int bufferSize; pthread_t thread; char main_buf[50]= {0}; int readlen; result = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets); if(-1 == result) { printf("socketpair error!\n"); return -1; } /* 创建一个子线程用于和主线程之间进行双向通讯 */ result = pthread_create(&thread, NULL, thread_run_func, (void *)sockets[1]); sleep(1); /* 延时一段时间让子进程先于主进程运行 */ /* 接收子进程发送过来的消息 */ readlen = read(sockets[0], main_buf, 50); main_buf[readlen] = '\0'; printf("recv from child thread : %s\n", main_buf); /* 发送一个消息给子进程 */ printf("send to child thread : %s\n", "Hi,child"); write(sockets[0], "Hi,child", sizeof("Hi,child")); sleep(1); return 0; }

    运行结果:

    Processed: 0.013, SQL: 9