函数原型:
#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