linux socketpair通讯

#include <pthread.h>
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>






#define MAX_BUF_SIZE  (500)


void *function_thread1(void *arg)
{
    int fd = *(int*)arg;
    char buf[MAX_BUF_SIZE + 1];
    int cnt = 0;
    
    while(1)
    {
        /* write to main thread*/
        sprintf(buf,"say hello to main thread %d \r\n",cnt++);    
        write(fd,buf,MAX_BUF_SIZE);


        /*read fron main thread*/
        memset(buf,0,sizeof(buf));
        read(fd,buf,MAX_BUF_SIZE);
        printf("%s",buf);


        /*休眠*/
        sleep(5);
    }
    
    return NULL;
}


int main()
{
    int sockets[2];
    pthread_t threadId;
    int ret = 0;
    int mainFd;
    int threadFd;
    int cnt = 0;
    char buf[MAX_BUF_SIZE + 1];


    /*创建socketpair*/
    ret = socketpair(AF_UNIX, SOCK_STREAM,0, sockets);
    if(ret != 0)
    {
        perror("can't create socketpair: ");
        return -1;
    }


    threadFd = sockets[0];
    mainFd = sockets[1];
    ret = pthread_create(&threadId,NULL,function_thread1,&threadFd);
    if(ret != 0)
    {
        perror("can't create thread: ");
        return -1;
    }


    while(1)
    {
        /*read fron thread1*/
        memset(buf,0,sizeof(buf));
        read(mainFd,buf,MAX_BUF_SIZE);
        printf("mainthread read:%s",buf);


        /* write to thread1*/
        sprintf(buf,"say hello to thread1 %d \r\n",cnt++);
        write(mainFd,buf,MAX_BUF_SIZE);
    }
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值