socketpair的使用


socketpair函数概要如下:
#include <sys/types.h>
#include <sys/socket.h>
int socketpair(int domain, int type, int protocol, int sv[2]);
sys/types.h文件需要用来定义一些C宏常量。sys/socket.h文件必须包含进来定义socketpair函数原型。
socketpair函数需要四个参数。他们是:
套接口的域
套接口类型
使用的协议
指向存储文件描述符的指针

类型参数声明了我们希望创建哪种类型的套接口。socketpair函数的选择如下:
SOCK_STREAM
SOCK_DGRAM
对于socketpair函数,protocol参数必须提供为0。
参数sv[2]是接收代表两个套接口的整数数组。每一个文件描述符代表一个套接口,并且与另一个并没有区别。
如果函数成功,将会返回0值。否则将会返回-1表明创建失败,并且errno来表明特定的错误号。

关于流程。socketpair()函数创建出两个进程,fork()之后这两个进程都会执行主程序中的代码,这个一定要注意!尤其是bind的时候,如果bind两次的话,那就会出错了。一般会在子进程里调用一个带死循环的函数,这样就好了。(这个情况的例子会在综合运用中讲解)

一下给出个简单的例子。

// 建立socket对
       #include <sys/types.h>
       #include <sys/socket.h>
    
       #include <stdlib.h>
       #include <stdio.h>
    
       int main ()
       {
         int fd[2];
   
        int r = socketpair( AF_UNIX, SOCK_STREAM, 0, fd );
        if ( r < 0 ) {
          perror( "socketpair()" );
          exit( 1 );
        }
   
        if ( fork() ) {
          /* Parent process: echo client */
          int val = 0;
          close( fd[1] );
          while ( 1 ) {
            sleep( 1 );
            ++val;
            printf( "Sending data: %d/n", val );
            write( fd[0], &val, sizeof(val) );
            read( fd[0], &val, sizeof(val) );
            printf( "Data received: %d/n", val );
          }
        }
        else {
          /* Child process: echo server */
          int val;
          close( fd[0] );
          while ( 1 ) {
            read( fd[1], &val, sizeof(val) );
            ++val;
            write( fd[1], &val, sizeof(val) );
          }
        }
      }

在给出一个用sendmsg来传递数据的例子

/*****************************************
 *
 * Listing 1.2
 *
 * Example performing I/O on s socket pair:
 *
 * ******************************************/
#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;
}

  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
socketpair是一组用于创建全双工通信管道的函数。它可以在内核中创建一对已连接的套接字,这对套接字之间可以进行双向通信,类似于管道。 socketpair函数的原型如下: ```c #include <sys/types.h> #include <sys/socket.h> int socketpair(int domain, int type, int protocol, int sv[2]); ``` 参数说明: - domain:地址族,可以是AF_INET(IPv4)、AF_INET6(IPv6)或AF_UNIX(本地套接字)。 - type:套接字类型,可以是SOCK_STREAM(流式套接字)或SOCK_DGRAM(数据报套接字)。 - protocol:协议类型,一般为0,表示自动选择。 - sv:指向套接字文件描述符的数组,其中sv[0]表示第一个套接字,sv[1]表示第二个套接字。 使用socketpair函数创建套接字对后,可以使用fork函数来创建子进程,子进程可以通过套接字与父进程通信,实现进程间通信。 下面是一个简单的例子,演示了socketpair函数的使用: ```c #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> int main() { int sv[2]; char buf[1024]; if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0) { perror("socketpair"); return -1; } if (fork() == 0) { // 子进程 close(sv[0]); write(sv[1], "hello from child", 16); read(sv[1], buf, sizeof(buf)); printf("%s\n", buf); } else { // 父进程 close(sv[1]); write(sv[0], "hello from parent", 17); read(sv[0], buf, sizeof(buf)); printf("%s\n", buf); } return 0; } ``` 该例子中创建了一个AF_UNIX域的套接字对,其中父进程向子进程发送了一条消息并等待子进程的回复,子进程读取了父进程发送的消息并回复了一条消息给父进程。运行该程序可以看到如下输出: ``` hello from child hello from parent ``` 可以看到子进程和父进程之间通过socketpair函数创建的套接字进行了双向通信。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值