php利用socket_pair进程通信,socketpair实现进程通信

pipe用来创建管道,但是单个管道只能单向通信,一端用于读,而另一端用于写。如果要实现进程双向通信,必须创建一对管道。具体实现忽略。而socketpair则可以用来创建双向通信的管道。取决于底层实现,打开的还是一个文件,fd[0],fd[1],管道中f[0]读端,f[1]写端。

#include

#include

int socketpair(int domain, int type, int protocol, int sv[2]);

domain:选用AF_LOCAL;

type:SOCK_STREAM

protocol:默认0

239b41943c488ededd40109addab6003.png#include                                                                      

#include

#include

#include

#include

#include

#include

int main()

{

int fd[2];

if(socketpair(AF_LOCAL,SOCK_STREAM,0,fd)<0){

perror("sockpair");

return 1;

}

pid_t id=fork();

if(id<0){

perror("fork");

return 2;

}

else if(id==0){

close(fd[0]);

char buf[1024];

while(1)

{

ssize_t _s;

strcpy(buf,"hello bit");

write(fd[1],buf,strlen(buf));

_s=read(fd[1],buf,sizeof(buf)-1);

buf[_s]='\0';

printf("father->child%s\n",buf);

}

close(fd[1]);

}

else{

close(fd[1]);

char buf[1024];

while(1)

{

ssize_t _s=read(fd[0],buf,sizeof(buf)-1);

if(_s>0){

buf[_s]='\0';

printf("child -> father %s\n",buf);

}

strcpy(buf,"hello world");

write(fd[0],buf,strlen(buf));

}

close(fd[0]);

//wait child

}

return 0;

运行截图:

69a58e9acabbc294ca7bfea1bba6b103.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值