UNIX Domain Socket IPC(转)

socket API原本是为网络通讯设计的,但后来在socket的框架上发展出一种IPC机制,就是UNIX Domain Socket。虽然网络socket也可用于同一台主机的进程间通讯(通过loopback地址127.0.0.1),但是UNIX Domain Socket用于IPC更有效率:不需要经过网络协议栈,不需要打包拆包、计算校验和、维护序号和应答等,只是将应用层数据从一个进程拷贝到另一个进程。这是因为,IPC机制本质上是可靠的通讯,而网络协议是为不可靠的通讯设计的。UNIX Domain Socket也提供面向流和面向数据包两种API接口,类似于TCP和UDP,但是面向消息的UNIX Domain Socket也是可靠的,消息既不会丢失也不会顺序错乱。

    UNIX Domain Socket是全双工的,API接口语义丰富,相比其它IPC机制有明显的优越性,目前已成为使用最广泛的IPC机制,比如X Window服务器和GUI程序之间就是通过UNIX Domain Socket通讯的。

    使用UNIX Domain Socket的过程和网络socket十分相似,也要先调用socket()创建一个socket文件描述符,address family指定为AF_UNIX,type可以选择SOCK_DGRAM或SOCK_STREAM,protocol参数仍然指定为0即可。

    UNIX Domain Socket与网络socket编程最明显的不同在于地址格式不同,用结构体sockaddr_un表示,网络编程的socket地址是IP地址加端口号,而UNIX Domain Socket的地址是一个socket类型的文件在文件系统中的路径,这个socket文件由bind()调用创建,如果调用bind()时该文件已存在,则bind()错误返回。

    以下程序将UNIX Domain socket绑定到一个地址。

[cpp]  view plain copy
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <stddef.h>  
  4. #include <sys/socket.h>  
  5. #include <sys/un.h>  
  6.   
  7. <pre class="programlisting" name="code">#include <stdlib.h>  
  8. #include <stdio.h>  
  9. #include <stddef.h>  
  10. #include <sys/socket.h>  
  11. #include <sys/un.h>  
  12.   
  13. int main(void)  
  14. {  
  15.     int fd, size;  
  16.     struct sockaddr_un un;  
  17.   
  18.     memset(&un, 0, sizeof(un));  
  19.     un.sun_family = AF_UNIX;  
  20.     strcpy(un.sun_path, "foo.socket");  
  21.     if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {  
  22.         perror("socket error");  
  23.         exit(1);  
  24.     }  
  25.     size = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);  
  26.     if (bind(fd, (struct sockaddr *)&un, size) < 0) {  
  27.         perror("bind error");  
  28.         exit(1);  
  29.     }  
  30.     printf("UNIX domain socket bound\n");  
  31.     exit(0);  
  32. }  
  33. 注意程序中的offsetof宏,它在stddef.h头文件中定义: 
  34. #define offsetof(TYPE, MEMBER) ((int)&((TYPE *)0)->MEMBER) 
  35. offsetof(struct sockaddr_un, sun_path) 就是取 sockaddr_un 结构体的 sun_path 成员在结构体中的偏移,也就是从结构体的第几个字节开始是sun_path成员。想一想,这个宏是如何实现这一功能的?
  36. 该程序的运行结果如下。
  37. $ ./a.out  
  38. UNIX domain socket bound  
  39. $ ls -l foo.socket  
  40. srwxrwxr-x 1 user        0 Aug 22 12:43 foo.socket  
  41. $ ./a.out  
  42. bind error: Address already in use  
  43. $ rm foo.socket  
  44. $ ./a.out  
  45. UNIX domain socket bound  

  46.     以下是服务器的listen模块,与网络socket编程类似,在bind之后要listen,表示通过bind的地址(也就是socket文件)提供服务。
  47. #include <stddef.h>  
  48. #include <sys/socket.h>  
  49. #include <sys/un.h>  
  50. #include <errno.h>  
  51.   
  52. #define QLEN 10  
  53.   
  54. /* 
  55.  * Create a server endpoint of a connection. 
  56.  * Returns fd if all OK, <0 on error. 
  57.  */  
  58. int serv_listen(const char *name)  
  59. {  
  60.     int                 fd, len, err, rval;  
  61.     struct sockaddr_un  un;  
  62.   
  63.     /* create a UNIX domain stream socket */  
  64.     if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)  
  65.         return(-1);  
  66.     unlink(name);   /* in case it already exists */  
  67.   
  68.     /* fill in socket address structure */  
  69.     memset(&un, 0, sizeof(un));  
  70.     un.sun_family = AF_UNIX;  
  71.     strcpy(un.sun_path, name);  
  72.     len = offsetof(struct sockaddr_un, sun_path) + strlen(name);  
  73.   
  74.     /* bind the name to the descriptor */  
  75.     if (bind(fd, (struct sockaddr *)&un, len) < 0) {  
  76.         rval = -2;  
  77.         goto errout;  
  78.     }  
  79.     if (listen(fd, QLEN) < 0) { /* tell kernel we're a server */  
  80.         rval = -3;  
  81.         goto errout;  
  82.     }  
  83.     return(fd);  
  84.   
  85. errout:  
  86.     err = errno;  
  87.     close(fd);  
  88.     errno = err;  
  89.     return(rval);  
  90. }
  91.     以下是服务器的accept模块,通过accept得到客户端地址也应该是一个socket文件,如果不是socket文件就返回错误码,如果是socket文件,在建立连接后这个文件就没有用了,调用unlink把它删掉,通过传出参数uidptr返回客户端程序的user id。
  92. #include <stddef.h>  
  93. #include <sys/stat.h>  
  94. #include <sys/socket.h>  
  95. #include <sys/un.h>  
  96. #include <errno.h>  
  97.   
  98. int serv_accept(int listenfd, uid_t *uidptr)  
  99. {  
  100.     int                 clifd, len, err, rval;  
  101.     time_t              staletime;  
  102.     struct sockaddr_un  un;  
  103.     struct stat         statbuf;  
  104.   
  105.     len = sizeof(un);  
  106.     if ((clifd = accept(listenfd, (struct sockaddr *)&un, &len)) < 0)  
  107.         return(-1);     /* often errno=EINTR, if signal caught */  
  108.   
  109.     /* obtain the client's uid from its calling address */  
  110.     len -= offsetof(struct sockaddr_un, sun_path); /* len of pathname */  
  111.     un.sun_path[len] = 0;           /* null terminate */  
  112.   
  113.     if (stat(un.sun_path, &statbuf) < 0) {  
  114.         rval = -2;  
  115.         goto errout;  
  116.     }  
  117.   
  118.     if (S_ISSOCK(statbuf.st_mode) == 0) {  
  119.         rval = -3;      /* not a socket */  
  120.         goto errout;  
  121.     }  
  122.   
  123.     if (uidptr != NULL)  
  124.         *uidptr = statbuf.st_uid;   /* return uid of caller */  
  125.     unlink(un.sun_path);        /* we're done with pathname now */  
  126.     return(clifd);  
  127.   
  128. errout:  
  129.     err = errno;  
  130.     close(clifd);  
  131.     errno = err;  
  132.     return(rval);  
  133. } 
  134.     以下是客户端的connect模块,与网络socket编程不同的是,UNIX Domain Socket客户端一般要显式调用bind函数,而不依赖系统自动分配的地址。客户端bind一个自己指定的socket文件名的好处是,该文件名可以包含客户端的pid以便服务器区分不同的客户端。
  135. #include <stdio.h>  
  136. #include <stddef.h>  
  137. #include <sys/stat.h>  
  138. #include <sys/socket.h>  
  139. #include <sys/un.h>  
  140. #include <errno.h>  
  141.   
  142. #define CLI_PATH    "/var/tmp/"      /* +5 for pid = 14 chars */  
  143.   
  144. /* 
  145.  * Create a client endpoint and connect to a server. 
  146.  * Returns fd if all OK, <0 on error. 
  147.  */  
  148. int cli_conn(const char *name)  
  149. {  
  150.     int                fd, len, err, rval;  
  151.     struct sockaddr_un un;  
  152.   
  153.     /* create a UNIX domain stream socket */  
  154.     if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)  
  155.         return(-1);  
  156.   
  157.     /* fill socket address structure with our address */  
  158.     memset(&un, 0, sizeof(un));  
  159.     un.sun_family = AF_UNIX;  
  160.     sprintf(un.sun_path, "%s%05d", CLI_PATH, getpid());  
  161.     len = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);  
  162.   
  163.     unlink(un.sun_path);        /* in case it already exists */  
  164.     if (bind(fd, (struct sockaddr *)&un, len) < 0) {  
  165.         rval = -2;  
  166.         goto errout;  
  167.     }  
  168.   
  169.     /* fill socket address structure with server's address */  
  170.     memset(&un, 0, sizeof(un));  
  171.     un.sun_family = AF_UNIX;  
  172.     strcpy(un.sun_path, name);  
  173.     len = offsetof(struct sockaddr_un, sun_path) + strlen(name);  
  174.     if (connect(fd, (struct sockaddr *)&un, len) < 0) {  
  175.         rval = -4;  
  176.         goto errout;  
  177.     }  
  178.     return(fd);  
  179.   
  180. errout:  
  181.     err = errno;  
  182.     close(fd);  
  183.     errno = err;  
  184.     return(rval);  
  185. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值