socketpair函数的作用

2014/09/2516:04:05 1

       今天在阅读nginx源码时发现socketpair这个函数,开始还以为是nginx中自定义的函数,man一下后才发现,还有父子进程间通讯的作用,以下是该函数的说明:
SOCKETPAIR(2)              Linux Programmer’s Manual             SOCKETPAIR(2)

NAME
       socketpair - create a pair of connected sockets

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

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

DESCRIPTION
       The socketpair() call creates an unnamed pair of connected sockets in the specified domain, of the specified
       type, and using the optionally specified protocol.  For further details of these arguments, see socket(2).

       The descriptors used in referencing the new sockets are returned in sv[0] and sv[1].  The  two  sockets  are
       indistinguishable.

RETURN VALUE
       On success, zero is returned.  On error, -1 is returned, and errno is set appropriately.

以下是一个父子进程通讯的例子:

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

int main(int argc,char **argv)
{
    int z;        /* Status return code */
    int s[2];    /* Pair of sockets */
 struct msghdr msg;
    struct iovec iov[1];
 char send_buf[100] = "TEST";
 struct msghdr msgr;
    struct iovec iovr[1];
    char recv_buf[100];


    /*
     * Create a pair of local sockets:
     */
    z = socketpair(AF_LOCAL,SOCK_STREAM,0,s);

    if(z == -1)
    {
        fprintf(stderr,
                "%s:socketpair(AF_LOCAL,SOCK_STREAM,""0)/n",strerror(errno));
        return 1;    /* Failed */
    }

    /*
     * Sendmsg s[1]:
     */

         bzero(&msg, sizeof(msg));
         msg.msg_name = NULL;        /* attention this is a pointer to void* type */
         msg.msg_namelen = 0;
         iov[0].iov_base = send_buf;
         iov[0].iov_len = sizeof(send_buf);
         msg.msg_iov = iov;
         msg.msg_iovlen = 1;

    printf("sendmsg begin./n");
   z = sendmsg( s[1], &msg, 0 );
   if(z == -1 )
   {
    fprintf(stderr,"Sendmsg failed.  errno : %s/n",strerror(errno));
    return -1;
   }
    printf("Sendmsg Success!/n");

    /*
     * Read from socket s[0]:
     */

         bzero(&msg, sizeof(msg));
         msgr.msg_name = NULL;        /* attention this is a pointer to void* type */
         msgr.msg_namelen = 0;
         iovr[0].iov_base = &recv_buf;
         iovr[0].iov_len = sizeof(recv_buf);
         msgr.msg_iov = iovr;
         msgr.msg_iovlen = 1;

         z = recvmsg(  s[0], &msgr, 0);
   if(z == -1 )
   {
    fprintf(stderr,"Recvmsg failed.  errno : %s/n",strerror(errno));
    return -1;
   }
    printf("Recvmsg Success!/n");
 printf("recvmsg : %s/n", recv_buf);

    /*
     * Close the sockets:
     */
    close(s[0]);
    close(s[1]);

    puts("Done");
    return 0;
}

  • 微信扫码赞助
  • weinxin
  • 支付宝赞助
  • weinxin

发表评论

您必须才能发表评论!

目前评论:1   其中:访客  0   博主  0

    • hellow Admin

      Very good