socketpair 进程间全双工通信

include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
using namespace std;
void err_sys(const char *errmsg);
class Person
{
  public:
   void say(string str )
   {
     int n;
     printf("%s say %s\n",name_.c_str(),str.c_str());
     if((n = write(say_sock_, str.c_str(), str.size() ))<0)
     {
        err_sys("write error!\n");
     }
   }
   string hear()
   {
     int n;
     string res;
     char s[1024];
     if ((n = read(hear_sock_,s , sizeof(s))) >0)
     {
        s[n]=0;
        res += s;
     }
     printf("%s hear %s\n",name_.c_str(),res.c_str());
     return res;
   }
   int say_sock_;
   int hear_sock_;
   Person()
   {
     say_sock_ = -1;
hear_sock_ = -1;
   }
   string name_;
};
int main(void)
{
        int sockfd1[2];
        pid_t pid;
        Person p1,p2;
        p1.name_="p1";
        p2.name_ = "p2";
        if ((socketpair(AF_LOCAL, SOCK_STREAM, 0, sockfd1))<0)
                err_sys("socketpair");
        if ((pid = fork()) == -1)
                err_sys("fork");
        else if (pid == 0)
        { /* child process */
                        p1.say_sock_ = sockfd1[0];
                        p1.hear_sock_ = sockfd1[0];

                        p1.say("hello world");
                        p1.hear();
                        p1.say("chile");
                        sleep(1);
        }
        else if (pid > 0)
        { /* parent process */
                        p2.hear_sock_ = sockfd1[1];
                        p2.say_sock_ = sockfd1[1];
                        p2.say("chifanlema ?");
                        p2.hear();
                        sleep(1);
        }
        return 0;
}
void err_sys(const char *errmsg)
{
        perror(errmsg);
        exit(1);
}
     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值