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);
}
socketpair 进程间全双工通信
最新推荐文章于 2023-02-02 20:34:42 发布