您的位置:首页 > 大数据 > 人工智能

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: