管道pipe是半双工的,pipe两次才能实现全双工,使得复杂。socketpair直接就可以实现全双工
socketpair对两个文件描述符中的任何一个都可读和可写,而pipe是一个读,一个写
管道pipe的fd[2],其中fd[0]代表读端,fd[1] 代表写端,数据下标对应读写功能,不能更改顺序。
socketpair的fd[2] ,两种情况
子进程: 使用 fd[0],close(fd[1]) 父进程:使用:fd[1] ,close(fd[0])
子进程: 使用:fd[1],close(fd[0]) 父进程: 使用fd[0],close(fd[1])
详间代码:
一:pipe实现父子进程全双工通信:
#include#include 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: %d\n", val ); write( fd1[1], &val, sizeof(val) ); read( fd2[0], &val, sizeof(val) ); printf( "parent Data received: %d\n", 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: %d\n", val ); ++val; write( fd2[1], &val, sizeof(val) ); printf( "son send received: %d\n", 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: 4parent Data received: 4
一:soketpair实现父子进程全双工通信:
#include#include #include #include 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: %d\n", val ); write( fd[0], &val, sizeof(val) ); read( fd[0], &val, sizeof(val) ); printf( "parent Data received: %d\n", val ); } } else { /* Child process: echo server */ int val ; close( fd[0] ); while ( 1 ) { read( fd[1], &val, sizeof(val) ); printf( "son Data received: %d\n", val ); ++val; write( fd[1], &val, sizeof(val) ); printf( "son send received: %d\n", 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: 4parent Data received: 4