linux下socketpair通信

函数原型:

       #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>

       int socketpair(int domain, int type, int protocol, int sv[2]);

函数功能描述:

socketpair函数创建两个随后连接起来的套接字,在nginx中master进程与worker进程就是通过socketpair创建的全双工流管道来通信的。

例子:

include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/socket.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    int channel[2];
    pid_t pid;
    int nbytes = 0;
    char buff[1024];
    char string[1024] = "hello,world";

    if(socketpair(AF_UNIX,SOCK_STREAM,0,channel) == -1)
    {
        printf("create unnamed socket pair failed:%s\n",strerror(errno) );
        exit(-1);
    }
    pid = fork();
    if (pid < 0)
    {
        perror("fork error");
        exit(-1);
    }
    if(pid == 0)
    {
        printf("Child process's pid is :%d\n",getpid());
        close(channel[0]);
        if((nbytes = read(channel[1], buff, sizeof(buff))) == -1)
        {
            perror("child read error");
            exit(-1);
        }
        printf("Child process read string from channel[1]: %s \n", buff);
        if((nbytes = write(channel[1], string, strlen(string))) == -1)
        {
            perror("child write error");
            exit(-1);
        }
        printf("Child process write string to channel[0]: %s\n", string);
        close(channel[1]);
        exit(0);
    }

    printf("Parent process's pid is %d\n",getpid());
    close(channel[1]);
    if((nbytes = write(channel[0], string, strlen(string))) == -1)
    {
        perror("parent write error\n");
        exit(-1);
    }
    printf("Parent process write string to channel[0]: %s\n", string);
    memset(buff, 0, sizeof(buff));
    sleep(3);
    if((nbytes = read(channel[0], buff, sizeof(buff))) == -1)
    {
        perror("parent read error");
        exit(-1);
    }
    printf("Parent process read string from channel[1]: %s \n", buff);

    close(channel[0]);
    waitpid(pid, NULL, 0);
    exit(0);
}

运行结果:

Parent process's pid is 22196
Parent process write string to channel[0]: hello,world
Child process's pid is :22197
Child process read string from channel[1]: hello,world 
Child process write string to channel[0]: hello,world
Parent process read string from channel[1]: hello,world 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值