socketpair

socketpair创建全双工管道
直接的办法当然是pipe两次,创建两组管道,但是有没有更简单的呢?
socketpair就可以了,man socketpair:
socketpair - create a pair of connected sockets, The two sockets are indistinguishable,也就是说,用socketpair创建出来的两个描述符应该是等价的。

#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void err_sys(const char *errmsg)
{
    perror(errmsg);
    exit(1);
}

int main(void)
{
    int sockfd[2];
    pid_t pid;

    if ((socketpair(AF_LOCAL, SOCK_STREAM, 0, sockfd)) < 0) {
        err_sys("socketpair");
    }

    if ((pid = fork()) == -1) {
        err_sys("fork");
    } else if (pid == 0) {
        char s[BUFSIZ];
        ssize_t n;
        close(sockfd[1]); //write port

        if ((n = read(sockfd[0], s, sizeof(s))) < 0) {
            err_sys("read error!\n");
        }

        printf("read:%s\n",s);
        close(sockfd[0]);
        exit(0);
    } else if (pid > 0) {
        char buf[] = "hello china";
        ssize_t n;
        close(sockfd[0]); //read port

        if ((n = write(sockfd[1], buf, sizeof(buf))) < 0) {
            err_sys("write error!\n");
        }

        close(sockfd[1]);
        wait(NULL);
    }

    return 0;
}

这个例子只写了单向传输,应该可以双工制的,看来得再找个例子了。

//双工工作方式
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #define DATA1 "test string 1" #define DATA2 "test string 2" void main() { int sockets[2], child; char buf[1024]; /* Get the socket pair */ if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) { printf("error %d on socketpair ", errno); exit(1); } /* create child process */ if ((child = fork()) == -1) { printf("fork error %d ", errno); exit(1); } if (child != 0) { /* this is the parent */ /* close child's end of socket */ close(sockets[0]); /* read message from child */ if (read(sockets[1], buf, sizeof(buf)) < 0) { printf("error %d reading socket ", errno); exit(1); } printf("parent:-->%s \n", buf); /* write message to child */ if (write(sockets[1], DATA1, sizeof(DATA1)) < 0) { printf("error %d writing socket ", errno); exit(1); } /* finished */ close(sockets[1]); } else { /* the child */ /* close parent's end of socket */ close(sockets[1]); /* send message to parent */ if (write(sockets[0], DATA2, sizeof(DATA1)) < 0) { printf("error %d writing socket ", errno); exit(1); } /* get message from parent */ if (read(sockets[0], buf, sizeof(buf)) < 0) { printf("error %d reading socket ", errno); exit(1); } printf("child: -->%s\n ", buf); /* finished */ close(sockets[0]); } }

父进程从sockets[1]中读写,子进程从sockets[0]中读写,的确是全双工形态。
唯一值得考虑的是为什么在父子进程中,要分别关闭sockets[0]和sockets[1]呢?

posted @ 2015-04-30 10:27  牧 天  阅读(448)  评论(0)    收藏  举报