概述
管道pipe是半双工的,pipe两次才能实现全双工,使得代码复杂。socketpair直接就可以实现全双工
socketpair对两个文件描述符中的任何一个都可读和可写,而pipe是一个读,一个写
详间代码:
一:pipe实现父子进程全双工通信:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
int fd1[2],fd2[2];
pipe(fd1);
pipe(fd2);
if ( fork() ) {
/* Parent process: echo client */
int val = 0;
close( fd1[0] );
close(fd2[1]);
while ( 1 ) {
sleep( 1 );
++val;
printf( "parent Sending data: %dn", val );
write( fd1[1], &val, sizeof(val) );
read( fd2[0], &val, sizeof(val) );
printf( "parent Data received: %dn", val );
}
}
else {
/* Child process: echo server */
int val ;
close( fd1[1] );
close(fd2[0]);
while ( 1 ) {
read( fd1[0], &val, sizeof(val) );
printf( "son Data received: %dn", val );
++val;
write( fd2[1], &val, sizeof(val) );
printf( "son send received: %dn", val );
}
}
}
输出结果:parent Sending data: 1
son Data received: 1
son send received: 2
parent Data received: 2
parent Sending data: 3
son Data received: 3
son send received: 4
parent Data received: 4
一:soketpair实现父子进程全双工通信:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
int main ()
{
int fd[2];
int r = socketpair( AF_UNIX, SOCK_STREAM, 0, fd );
if ( r < 0 ) {
perror( "socketpair()" );
exit( 1 );
}
if ( fork() ) {
/* Parent process: echo client */
int val = 0;
close( fd[1] );
while ( 1 ) {
sleep( 1 );
++val;
printf( "parent Sending data: %dn", val );
write( fd[0], &val, sizeof(val) );
read( fd[0], &val, sizeof(val) );
printf( "parent Data received: %dn", val );
}
}
else {
/* Child process: echo server */
int val ;
close( fd[0] );
while ( 1 ) {
read( fd[1], &val, sizeof(val) );
printf( "son Data received: %dn", val );
++val;
write( fd[1], &val, sizeof(val) );
printf( "son send received: %dn", val );
}
}
}
输出结果:parent Sending data: 1
son Data received: 1
son send received: 2
parent Data received: 2
parent Sending data: 3
son Data received: 3
son send received: 4
parent Data received: 4
最后
以上就是大力面包为你收集整理的进程通信:管道(pipe)和socketpair区别的全部内容,希望文章能够帮你解决进程通信:管道(pipe)和socketpair区别所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复