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 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章