socketpair 使用

来源:互联网 发布:锤子大爆炸软件下载 编辑:程序博客网 时间:2024/06/14 18:29


#include <stdio.h> #include <sys/socket.h>#include <sys/types.h>int main(){    int sync_fds[2];    if(socketpair(AF_UNIX, SOCK_STREAM, 0, sync_fds)){        perror("socketpair failed...\n");        return 0;    }    int child_pid = fork();    if(child_pid == -1){        perror("fork failed ...\n");        close(sync_fds[0]);        close(sync_fds[1]);        return 0;    }    if(child_pid){        close(sync_fds[0]);        char buff;        while(1){            sleep(1);            send(sync_fds[1], "C", 1, MSG_NOSIGNAL);            printf("parent: send c ....\n");            read(sync_fds[1], &buff, 1);            printf("parent: read %s\n", &buff);        }    }else{        close(sync_fds[1]);        char buff;        while(1){            int read_ret = read(sync_fds[0], &buff, 1);            printf("child read %s\n", &buff);            send(sync_fds[0], "D", 1, MSG_NOSIGNAL);            printf("child send d ...\n");        }    }    return 0;}


输出结果:

parent: send c ....child read Cchild send d ...parent: read Dparent: send c ....child read Cchild send d ...parent: read Dparent: send c ....child read Cchild send d ...parent: read D