socket通信之socketpair

这篇文章主要介绍的是socketpair()函数,至于函数的详细介绍,大家可以参看:man socketpair 介绍的还是可以的。下面是中文简介:
函数原型
#include <sys/types.h> 
#include <sys/socket.h> 
int socketpair(int d, int type, int protocol, int sv[2]); 
参数介绍:
socketpair()函数建立一对匿名的已经连接的套接字,其特性由协议族d、类型type、协议protocol决定,建立的两个套接字描述符会放在sv[0]和sv[1]中。
socketpair()函数的原型如下,第1个参数d,表示协议族,只能为AF_LOCAL或者AF_UNIX;
第2个参数type,表示类型,只能为0。
第3个参数protocol,表示协议,可以是SOCK_STREAM或者SOCK_DGRAM。用SOCK_STREAM建立的套接字对是管道流,与一般的管道相区别的是,套接字对建立的通道是双向的,即每一端都可以进行读写。参数sv,用于保存建立的套接字对。
下面是代码:

#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 */
        char *cp;    /* A work pointer */
        char buf[80];    /* work buffer */
        z = socketpair(AF_LOCAL,SOCK_STREAM,0,s);
        if(z == -1)
        {
                printf("creat spcketpair error\n");
                return 1;    /* Failed */
        }
        z = write(s[1],"Hello?",6);
        if(z<0)
        {
                printf("write error\n");
                return 2;    /* Failed */
        }
        printf("write hello? to s[1]\n");
        z = read(s[0],buf,sizeof buf);
        if(z < 0)
        {
                printf("read error\n");
                return 3;    /* Failed */
        }
        printf("Recevie message '%s' from socket s[0]\n",buf);
        z = write(s[0],cp="Go away!",8);
        if(z < 0)
        {
                printf("write error");
                return 4;    /* Failed */
        }
        printf("write Go away! to s[1]\n");
        z = read(s[1],buf,sizeof buf);
        if(z < 0)
        {
                printf("read error\n");
                return 3;    /* Failed */
        }
        buf[z] = 0;    /*NUL terminate */
        printf("Received message '%s' from socket s[1]\n",buf);
        close(s[0]);
        close(s[1]);
        return 0;
}


你可能感兴趣的:(socket通信之socketpair)