socketpair函数

来源:互联网 发布:win10怎样卸载软件 编辑:程序博客网 时间:2024/05/19 22:46
   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 50int 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;}



0 0
原创粉丝点击