socketpair与管道pipe

本文通过示例代码对比了管道(pipe)与socketpair在实现线程间全双工通信的应用。介绍了两种方式的基本原理及代码实现过程,展示了如何在父子进程或线程之间进行双向数据交换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在看Android 输入系统的时候,第一次看到socketpair,发现和管道非常相似。唯他们的区别就是socketpair,默认支持全双工,而pipe是半双工的。他们一样只能用在父子进程或者线程之间通信。

下面分别以socketpair和管道实现全双工通信。

管道实现线程间全双工通信
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>

#define SIZE 1024

int fd1[2],fd2[2]; //fd1[0]:read,  fd1[1]:write

void *func_thread1(void *arg)
{
    char buf[SIZE] = {0};
    int cnt = 0;
    while(1)
    {
        sprintf(buf,"hello main  %d\n",cnt++);
        write(fd1[1],buf,strlen(buf));
        int len = read(fd2[0],buf,SIZE);
        buf[len] = '\0';
        printf("%s",buf);
        bzero(buf,SIZE);
        sleep(3);
    }
    return NULL;
}

int main(int agrc,char**argv)
{
    pthread_t thread1_t;

    /*1. create pipe*/
    pipe(fd1);
    pipe(fd2);
    /*2. create thread1*/
    pthread_create(&thread1_t, NULL,
                          func_thread1, NULL);
    char buf[SIZE] = {0};
    int cnt = 0;
    char * p = buf;
    printf("buf[SIZE] sizeof:%d,  strlen:%d\n",sizeof(buf),strlen(buf));
    printf(" char * p  sizeof:%d,  strlen:%d\n",sizeof(p),strlen(p));
    while(1){
        int len = read(fd1[0],buf,SIZE);
        buf[len] = '\0';
        printf("%s",buf);
        bzero(buf,SIZE);
        sprintf(buf,"hello thread  %d\n",cnt++);
        write(fd2[1],buf,strlen(buf));  
        sleep(3);
    }
    return 0;
}

Socketpair实现线程间全双工通信
#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

#define SIZE 1024

void *func_thread1(void *arg)
{
    char buf[SIZE] = {0};
    int cnt = 0;
    int fd = (int)arg;
    while(1)
    {
        sprintf(buf,"hello main  %d\n",cnt++);
        write(fd,buf,strlen(buf));
        int len = read(fd,buf,SIZE);
        buf[len] = '\0';
        printf("%s",buf);
        bzero(buf,SIZE);
        sleep(3);
    }
    return NULL;
}

int main(int agrc,char**argv)
{
    int fd[2];
    pthread_t thread1_t;

    /*1. create socketpair*/
    int ret = socketpair(AF_UNIX,SOCK_STREAM,0,fd);
    if(ret < 0){
        perror("socketpair");
        exit(-1);
    }
    /*2. create thread1*/
    pthread_create(&thread1_t, NULL,
                          func_thread1, fd[1]);
    char buf[SIZE] = {0};
    int cnt = 0;
    char * p = buf;

    while(1){
        int len = read(fd[0],buf,SIZE);
        buf[len] = '\0';
        printf("%s",buf);
        bzero(buf,SIZE);
        sprintf(buf,"hello thread  %d\n",cnt++);
        write(fd[0],buf,strlen(buf));   
        sleep(3);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值