socketpair函数
2014-02-21 20:10
176 查看
socketpair 函数仅适用于Unix域套接字,创建一个stream pipe,但是与pipe()调用不同在流管道是全双工的。既可以在同一个进程中读写,但更常见的是通过stream pipe进行父子进行的通信。
#include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUF_SIZE 50 int main(void){ int fd[2]; int error; char *str="hello , world!"; char buf[BUF_SIZE]; if(socketpair(AF_UNIX,SOCK_STREAM,0,fd) == -1){ printf("ERR:create socket pair failed:%s\n",strerror(errno)); exit(-1); } //在一个进程中,在流管道的一端写入,可以从另一端读取; if((error = write(fd[0],str,strlen(str))) == -1){ printf("ERR:write error:%s\n",strerror(errno)); exit(-1); } /* //在同一端写读会发生阻塞 if((error = read(fd[0],buf,sizeof(buf))) == -1){ printf("ERR:read error:%s\n",strerror(errno)); exit(-1); } */ if((error = read(fd[1],buf,sizeof(buf))) == -1){ printf("ERR:read error:%s\n",strerror(errno)); exit(-1); } printf("GET:%s\n",buf); return 0; }---------------
int main(void){ int fd[2]; int error; int pid; char *str="hello , world!"; char buf[BUF_SIZE]; if(socketpair(AF_UNIX,SOCK_STREAM,0,fd) == -1){ printf("ERR:create socket pair failed:%s\n",strerror(errno)); exit(-1); } if((pid = fork()) == 0){ //child process close(fd[1]); if((error = write(fd[0],str,strlen(str))) == -1){ printf("ERR:write error:%s\n",strerror(errno)); exit(-1); } }else if(pid > 0){ // parent process read close(fd[0]); if((error = read(fd[1],buf,sizeof(buf))) == -1){ printf("ERR:read error:%s\n",strerror(errno)); exit(-1); } printf("Get from child:%s\n",buf); }else{ printf("fork error!\n"); exit(-1); } return 0; }
相关文章推荐
- DDMS启动出现“Failed to initialize Monitor Thread: Unable to establish loopback connection”错误的解决方法
- "fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt"解决方案
- http://home.gongkong.com/profile/blogdetail.aspx?id=2013120610242900001
- Hadoop & Hbase on OSX 10.8 Mountain Lion
- org.codehaus.xfire.XFireRuntimeException: Could not invoke service.. Server returned error code = 404 for URI.. Check server logs for details
- Hypertable中Hyperspace的Failover
- Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
- 添加第三方类库造成的linker command failed with exit code 1 (use -v to see invocation)的错误调试
- 在 FlashDevelop 的移动项目 (Adobe AIR) 中使用 ane
- 根据给出的基类Animal和main()函数。
- GTK+2.0-----容器构件GtkContainer
- http://pan.baidu.com/s/1EHK5u#dir
- 等到花儿也谢了的await
- Megacli查看raid磁盘信息
- 改主机名后启weblogic失败,Could not obtain the localhost address. The most likely cause is an error in the ne
- 本地生成Rails API文档
- aio
- ibaits防止注入
- 转: AlphaImageLoader简介
- DBA亲,你们的RAID5阵列有保障吗?