与pipe的区别
pipe产生的文件描述符是半双工的,需要pipe两次才能实现全双工,产生的两个描述符是一个读,一个写
socketpair直接就可以全双工,产生的两个文件描述符的任何一个都可读可写
pipe例子
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(){
int fd1[2],fd2[2];
if(pipe(fd1) < 0 || pipe(fd2) < 0)
exit(-1);
if(fork()){
int val=0;
close(fd1[0]);
close(fd2[1]);
while(1){
sleep(1);
++val;
printf("parent send: %d
",val);
write(fd1[1],&val,sizeof(val));
read(fd2[0],&val,sizeof(val));
printf("parent received: %d
",val);
}
}else{
int val;
close(fd1[1]);
close(fd2[0]);
while(1){
read(fd1[0],&val,sizeof(val));
printf("son Data received: %d
",val);
++val;
write(fd2[1],&val,sizeof(val));
printf("son send: %d
",val);
}
}
}
socketpair例子
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
int fd[2];
int ret;
ret=socketpair(AF_LOCAL,SOCK_STREAM,0,fd);
if(ret < 0){
perror("socketpair");
exit(-1);
}
if(fork()){
int val=0;
close(fd[1]);
while(1){
sleep(1);
++val;
printf("parent sending data: %d
",val);
write(fd[0],&val,sizeof(val));
read(fd[0],&val,sizeof(val));
printf("parent Data received: %d
",val);
}
}else{
int val;
close(fd[0]);
while(1){
read(fd[1],&val,sizeof(val));
printf("son Data received: %d
",val);
++val;
write(fd[1],&val,sizeof(val));
printf("son send received: %d
",val);
}
}
}