特點:
sv【0】和sv【1】可讀可寫。每個進程固定用一個接口。
寫數據時:通道不滿不阻塞;
讀數據時:通道里沒數據時阻塞。可用fcntl設置爲非阻塞。
創建:
int socketpair(int domain, int type, int protocol, int sv【2】);
參數:
domain:
套接口的域:
AF_LOCAL--------現在用法
AF_UNIX-----------以前用法
兩個只是時間上的區別,歷史因素,都能用。
type:
套接口類型:
SOCK_STREAM------數據流(tcp)
SOCK_DGRAM--------數據報(udp)
protocol:
協議。
必須是0。
sv:
文件描述符的指針。
sv【0】和sv【1】都可讀寫。
返回值:
0--------成功
-1-------出錯
關閉:
close(sv【0】);
close(sv【1】);
圖解:
代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <fcntl.h>
int main(){
int sv[2];
if(-1 == socketpair(AF_LOCAL,SOCK_STREAM,0,sv)){
perror("socketpair error");
return 1;
}
printf("%d %d\n",sv[0],sv[1]);
if(fork()){
char str[]="Hello sockerpair\n";
write(sv[0],str,sizeof(str));
}else{
char buf[BUFSIZ];
read(sv[1],buf,BUFSIZ);
printf("read %s\n",buf);
fcntl(sv[1],F_SETFL,O_NONBLOCK);//無數據寫入時,設置爲讀取阻塞取消。
bzero(buf,BUFSIZ);
read(sv[1],buf,BUFSIZ);
printf("read %s\n",buf);
}
}