套接字(全双工)实现进程间通信

来源:互联网 发布:搜狗关键词优化排名 编辑:程序博客网 时间:2024/06/01 09:04

特点:

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);}}

结果:


原创粉丝点击