socketpair使用

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

// Linux环境下使用socketpair函数创造一对未命名的、相互连接的UNIX域套接字。

void err_sys(const char *errmsg);

int main(void)
{
    int sockfd[2]; // 其中sockfd[0]用于读, sockfd[1]用于写.
    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) { /* child process */
        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 ) { /* parent process */
        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");
        }
        printf("write:%s\n", buf);

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

    return 0;
}

void err_sys(const char *errmsg)
{
    perror(errmsg);
    exit(1);
}
</pre><pre code_snippet_id="642894" snippet_file_name="blog_20150413_3_3442200" name="code" class="cpp">




在我的测试结果里面, 是父进程先返回, 子进程后返回..



父子进程可以通过这个配对的套接字通信.....



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值