Linux下的IPC-UNIX Domain Socket

一、 概述

UNIX Domain Socket是在socket架構上發展起來的用於同一臺主機的進程間通訊(IPC),它不需要經過網絡協議棧,不需要打包拆包、計算校驗和、維護序號和應答等,只是將應用層數據從一個進程拷貝到另一個進程。UNIX Domain Socket有SOCK_DGRAM或SOCK_STREAM兩種工作模式,類似於UDP和TCP,但是面向消息的UNIX Domain Socket也是可靠的,消息既不會丟失也不會順序錯亂。

UNIX Domain Socket可用於兩個沒有親緣關係的進程,是全雙工的,是目前使用最廣泛的IPC機制,比如X Window服務器和GUI程序之間就是通過UNIX Domain Socket通訊的。

二、工作流程

UNIX Domain socket與網絡socket類似,可以與網絡socket對比應用。

上述二者編程的不同如下:

  • address family爲AF_UNIX
  • 因爲應用於IPC,所以UNIXDomain socket不需要IP和端口,取而代之的是文件路徑來表示“網絡地址”。這點體現在下面兩個方面。
  • 地址格式不同,UNIXDomain socket用結構體sockaddr_un表示,是一個socket類型的文件在文件系統中的路徑,這個socket文件由bind()調用創建,如果調用bind()時該文件已存在,則bind()錯誤返回。
  • UNIX Domain Socket客戶端一般要顯式調用bind函數,而不象網絡socket一樣依賴系統自動分配的地址。客戶端bind的socket文件名可以包含客戶端的pid,這樣服務器就可以區分不同的客戶端。

UNIX Domain socket的工作流程簡述如下(與網絡socket相同)。

服務器端:創建socket—綁定文件(端口)—監聽—接受客戶端連接—接收/發送數據—…—關閉

客戶端:創建socket—綁定文件(端口)—連接—發送/接收數據—…—關閉

三、阻塞和非阻塞(SOCK_STREAM方式)

讀寫操作有兩種操作方式:阻塞和非阻塞。

1.阻塞模式下

阻塞模式下,發送數據方和接收數據方的表現情況如同命名管道,參見本人文章“Linux下的IPC-命名管道的使用(http://blog.csdn.net/guxch/article/details/6828452)”

2.非阻塞模式

在send或recv函數的標誌參數中設置MSG_DONTWAIT,則發送和接收都會返回。如果沒有成功,則返回值爲-1,errno爲EAGAIN 或 EWOULDBLOCK。

四、測試代碼

 服務器端

  1. #include <stdio.h>   
  2. #include <sys/stat.h>   
  3. #include <sys/socket.h>   
  4. #include <sys/un.h>   
  5. #include <errno.h>   
  6. #include <stddef.h>   
  7. #include <string.h>   
  8.   
  9. // the max connection number of the server   
  10. #define MAX_CONNECTION_NUMBER 5   
  11.   
  12. /* * Create a server endpoint of a connection. * Returns fd if all OK, <0 on error. */  
  13. int unix_socket_listen(const char *servername)  
  14. {   
  15.   int fd;  
  16.   struct sockaddr_un un;   
  17.   if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)  
  18.   {  
  19.      return(-1);   
  20.   }  
  21.   int len, rval;   
  22.   unlink(servername);               /* in case it already exists */   
  23.   memset(&un, 0, sizeof(un));   
  24.   un.sun_family = AF_UNIX;   
  25.   strcpy(un.sun_path, servername);   
  26.   len = offsetof(struct sockaddr_un, sun_path) + strlen(servername);   
  27.   /* bind the name to the descriptor */   
  28.   if (bind(fd, (struct sockaddr *)&un, len) < 0)  
  29.   {   
  30.     rval = -2;   
  31.   }   
  32.   else  
  33.   {  
  34.       if (listen(fd, MAX_CONNECTION_NUMBER) < 0)      
  35.       {   
  36.         rval =  -3;   
  37.       }  
  38.       else  
  39.       {  
  40.         return fd;  
  41.       }  
  42.   }  
  43.   int err;  
  44.   err = errno;  
  45.   close(fd);   
  46.   errno = err;  
  47.   return rval;    
  48. }  
  49.   
  50. int unix_socket_accept(int listenfd, uid_t *uidptr)  
  51. {   
  52.    int clifd, len, rval;   
  53.    time_t staletime;   
  54.    struct sockaddr_un un;  
  55.    struct stat statbuf;   
  56.    len = sizeof(un);   
  57.    if ((clifd = accept(listenfd, (struct sockaddr *)&un, &len)) < 0)   
  58.    {  
  59.       return(-1);       
  60.    }  
  61.  /* obtain the client's uid from its calling address */   
  62.    len -= offsetof(struct sockaddr_un, sun_path);  /* len of pathname */  
  63.    un.sun_path[len] = 0; /* null terminate */   
  64.    if (stat(un.sun_path, &statbuf) < 0)   
  65.    {  
  66.       rval = -2;  
  67.    }   
  68.    else  
  69.    {  
  70.        if (S_ISSOCK(statbuf.st_mode) )   
  71.        {   
  72.           if (uidptr != NULL) *uidptr = statbuf.st_uid;    /* return uid of caller */   
  73.           unlink(un.sun_path);       /* we're done with pathname now */   
  74.           return clifd;        
  75.        }   
  76.        else  
  77.        {  
  78.           rval = -3;     /* not a socket */   
  79.        }  
  80.     }  
  81.    int err;  
  82.    err = errno;   
  83.    close(clifd);   
  84.    errno = err;  
  85.    return(rval);  
  86.  }  
  87.    
  88.  void unix_socket_close(int fd)  
  89.  {  
  90.     close(fd);       
  91.  }  
  92.   
  93. int main(void)  
  94. {   
  95.   int listenfd,connfd;   
  96.   listenfd = unix_socket_listen("foo.sock");  
  97.   if(listenfd<0)  
  98.   {  
  99.      printf("Error[%d] when listening...\n",errno);  
  100.      return 0;  
  101.   }  
  102.   printf("Finished listening...\n",errno);  
  103.   uid_t uid;  
  104.   connfd = unix_socket_accept(listenfd, &uid);  
  105.   unix_socket_close(listenfd);    
  106.   if(connfd<0)  
  107.   {  
  108.      printf("Error[%d] when accepting...\n",errno);  
  109.      return 0;  
  110.   }    
  111.    printf("Begin to recv/send...\n");    
  112.   int i,n,size;  
  113.   char rvbuf[2048];  
  114.   for(i=0;i<2;i++)  
  115.   {  
  116. //===========接收==============   
  117.    size = recv(connfd, rvbuf, 804, 0);     
  118.      if(size>=0)  
  119.      {  
  120.        // rvbuf[size]='\0';   
  121.         printf("Recieved Data[%d]:%c...%c\n",size,rvbuf[0],rvbuf[size-1]);  
  122.      }  
  123.      if(size==-1)  
  124.      {  
  125.          printf("Error[%d] when recieving Data:%s.\n",errno,strerror(errno));      
  126.              break;       
  127.      }  
  128. /* 
  129.  //===========發送============== 
  130.      memset(rvbuf, 'c', 2048); 
  131.          size = send(connfd, rvbuf, 2048, 0); 
  132.      if(size>=0) 
  133.      { 
  134.         printf("Data[%d] Sended.\n",size); 
  135.      } 
  136.      if(size==-1) 
  137.      { 
  138.          printf("Error[%d] when Sending Data.\n",errno);      
  139.              break;      
  140.      } 
  141. */  
  142.  sleep(30);  
  143.   }  
  144.    unix_socket_close(connfd);  
  145.    printf("Server exited.\n");      
  146.  }  
#include <stdio.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <stddef.h>
#include <string.h>

// the max connection number of the server
#define MAX_CONNECTION_NUMBER 5

/* * Create a server endpoint of a connection. * Returns fd if all OK, <0 on error. */
int unix_socket_listen(const char *servername)
{ 
  int fd;
  struct sockaddr_un un; 
  if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
  {
  	 return(-1); 
  }
  int len, rval; 
  unlink(servername);               /* in case it already exists */ 
  memset(&un, 0, sizeof(un)); 
  un.sun_family = AF_UNIX; 
  strcpy(un.sun_path, servername); 
  len = offsetof(struct sockaddr_un, sun_path) + strlen(servername); 
  /* bind the name to the descriptor */ 
  if (bind(fd, (struct sockaddr *)&un, len) < 0)
  { 
    rval = -2; 
  } 
  else
  {
	  if (listen(fd, MAX_CONNECTION_NUMBER) < 0)    
	  { 
		rval =  -3; 
	  }
	  else
	  {
	    return fd;
	  }
  }
  int err;
  err = errno;
  close(fd); 
  errno = err;
  return rval;	
}

int unix_socket_accept(int listenfd, uid_t *uidptr)
{ 
   int clifd, len, rval; 
   time_t staletime; 
   struct sockaddr_un un;
   struct stat statbuf; 
   len = sizeof(un); 
   if ((clifd = accept(listenfd, (struct sockaddr *)&un, &len)) < 0) 
   {
      return(-1);     
   }
 /* obtain the client's uid from its calling address */ 
   len -= offsetof(struct sockaddr_un, sun_path);  /* len of pathname */
   un.sun_path[len] = 0; /* null terminate */ 
   if (stat(un.sun_path, &statbuf) < 0) 
   {
      rval = -2;
   } 
   else
   {
	   if (S_ISSOCK(statbuf.st_mode) ) 
	   { 
		  if (uidptr != NULL) *uidptr = statbuf.st_uid;    /* return uid of caller */ 
	      unlink(un.sun_path);       /* we're done with pathname now */ 
		  return clifd;		 
	   } 
	   else
	   {
	      rval = -3;     /* not a socket */ 
	   }
    }
   int err;
   err = errno; 
   close(clifd); 
   errno = err;
   return(rval);
 }
 
 void unix_socket_close(int fd)
 {
    close(fd);     
 }

int main(void)
{ 
  int listenfd,connfd; 
  listenfd = unix_socket_listen("foo.sock");
  if(listenfd<0)
  {
     printf("Error[%d] when listening...\n",errno);
	 return 0;
  }
  printf("Finished listening...\n",errno);
  uid_t uid;
  connfd = unix_socket_accept(listenfd, &uid);
  unix_socket_close(listenfd);  
  if(connfd<0)
  {
     printf("Error[%d] when accepting...\n",errno);
     return 0;
  }  
   printf("Begin to recv/send...\n");  
  int i,n,size;
  char rvbuf[2048];
  for(i=0;i<2;i++)
  {
//===========接收==============
   size = recv(connfd, rvbuf, 804, 0);   
	 if(size>=0)
	 {
	   // rvbuf[size]='\0';
	    printf("Recieved Data[%d]:%c...%c\n",size,rvbuf[0],rvbuf[size-1]);
	 }
	 if(size==-1)
	 {
	     printf("Error[%d] when recieving Data:%s.\n",errno,strerror(errno));	 
             break;		
	 }
/*
 //===========發送==============
	 memset(rvbuf, 'c', 2048);
         size = send(connfd, rvbuf, 2048, 0);
	 if(size>=0)
	 {
		printf("Data[%d] Sended.\n",size);
	 }
	 if(size==-1)
	 {
	     printf("Error[%d] when Sending Data.\n",errno);	 
             break;		
	 }
*/
 sleep(30);
  }
   unix_socket_close(connfd);
   printf("Server exited.\n");    
 }


客戶端代碼

  1. #include <stdio.h>   
  2. #include <stddef.h>   
  3. #include <sys/stat.h>   
  4. #include <sys/socket.h>   
  5. #include <sys/un.h>   
  6. #include <errno.h>   
  7. #include <string.h>   
  8.   
  9. /* Create a client endpoint and connect to a server.   Returns fd if all OK, <0 on error. */  
  10. int unix_socket_conn(const char *servername)  
  11. {   
  12.   int fd;   
  13.   if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)    /* create a UNIX domain stream socket */   
  14.   {  
  15.     return(-1);  
  16.   }  
  17.   int len, rval;  
  18.    struct sockaddr_un un;            
  19.   memset(&un, 0, sizeof(un));            /* fill socket address structure with our address */  
  20.   un.sun_family = AF_UNIX;   
  21.   sprintf(un.sun_path, "scktmp%05d", getpid());   
  22.   len = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);  
  23.   unlink(un.sun_path);               /* in case it already exists */   
  24.   if (bind(fd, (struct sockaddr *)&un, len) < 0)  
  25.   {   
  26.      rval=  -2;   
  27.   }   
  28.   else  
  29.   {  
  30.     /* fill socket address structure with server's address */  
  31.       memset(&un, 0, sizeof(un));   
  32.       un.sun_family = AF_UNIX;   
  33.       strcpy(un.sun_path, servername);   
  34.       len = offsetof(struct sockaddr_un, sun_path) + strlen(servername);   
  35.       if (connect(fd, (struct sockaddr *)&un, len) < 0)   
  36.       {  
  37.           rval= -4;   
  38.       }   
  39.       else  
  40.       {  
  41.          return (fd);  
  42.       }  
  43.   }  
  44.   int err;  
  45.   err = errno;  
  46.   close(fd);   
  47.   errno = err;  
  48.   return rval;      
  49. }  
  50.    
  51.  void unix_socket_close(int fd)  
  52.  {  
  53.     close(fd);       
  54.  }  
  55.   
  56.   
  57. int main(void)  
  58. {   
  59.   srand((int)time(0));  
  60.   int connfd;   
  61.   connfd = unix_socket_conn("foo.sock");  
  62.   if(connfd<0)  
  63.   {  
  64.      printf("Error[%d] when connecting...",errno);  
  65.      return 0;  
  66.   }  
  67.    printf("Begin to recv/send...\n");    
  68.   int i,n,size;  
  69.   char rvbuf[4096];  
  70.   for(i=0;i<10;i++)  
  71.   {  
  72. /* 
  73.     //=========接收===================== 
  74.     size = recv(connfd, rvbuf, 800, 0);   //MSG_DONTWAIT 
  75.      if(size>=0) 
  76.      { 
  77.         printf("Recieved Data[%d]:%c...%c\n",size,rvbuf[0],rvbuf[size-1]); 
  78.      } 
  79.      if(size==-1) 
  80.      { 
  81.          printf("Error[%d] when recieving Data.\n",errno);    
  82.              break;      
  83.      } 
  84.          if(size < 800) break; 
  85. */  
  86.     //=========發送======================   
  87. memset(rvbuf,'a',2048);  
  88.          rvbuf[2047]='b';  
  89.          size = send(connfd, rvbuf, 2048, 0);  
  90.      if(size>=0)  
  91.      {  
  92.         printf("Data[%d] Sended:%c.\n",size,rvbuf[0]);  
  93.      }  
  94.      if(size==-1)  
  95.      {  
  96.         printf("Error[%d] when Sending Data:%s.\n",errno,strerror(errno));     
  97.             break;        
  98.      }  
  99.          sleep(1);  
  100.   }  
  101.    unix_socket_close(connfd);  
  102.    printf("Client exited.\n");      
  103.  }  
#include <stdio.h>
#include <stddef.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <string.h>

/* Create a client endpoint and connect to a server.   Returns fd if all OK, <0 on error. */
int unix_socket_conn(const char *servername)
{ 
  int fd; 
  if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)    /* create a UNIX domain stream socket */ 
  {
    return(-1);
  }
  int len, rval;
   struct sockaddr_un un;          
  memset(&un, 0, sizeof(un));            /* fill socket address structure with our address */
  un.sun_family = AF_UNIX; 
  sprintf(un.sun_path, "scktmp%05d", getpid()); 
  len = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);
  unlink(un.sun_path);               /* in case it already exists */ 
  if (bind(fd, (struct sockaddr *)&un, len) < 0)
  { 
  	 rval=  -2; 
  } 
  else
  {
	/* fill socket address structure with server's address */
	  memset(&un, 0, sizeof(un)); 
	  un.sun_family = AF_UNIX; 
	  strcpy(un.sun_path, servername); 
	  len = offsetof(struct sockaddr_un, sun_path) + strlen(servername); 
	  if (connect(fd, (struct sockaddr *)&un, len) < 0) 
	  {
		  rval= -4; 
	  } 
	  else
	  {
	     return (fd);
	  }
  }
  int err;
  err = errno;
  close(fd); 
  errno = err;
  return rval;	  
}
 
 void unix_socket_close(int fd)
 {
    close(fd);     
 }


int main(void)
{ 
  srand((int)time(0));
  int connfd; 
  connfd = unix_socket_conn("foo.sock");
  if(connfd<0)
  {
     printf("Error[%d] when connecting...",errno);
	 return 0;
  }
   printf("Begin to recv/send...\n");  
  int i,n,size;
  char rvbuf[4096];
  for(i=0;i<10;i++)
  {
/*
    //=========接收=====================
    size = recv(connfd, rvbuf, 800, 0);   //MSG_DONTWAIT
	 if(size>=0)
	 {
	    printf("Recieved Data[%d]:%c...%c\n",size,rvbuf[0],rvbuf[size-1]);
	 }
	 if(size==-1)
	 {
	     printf("Error[%d] when recieving Data.\n",errno);	 
             break;		
	 }
         if(size < 800) break;
*/
    //=========發送======================
memset(rvbuf,'a',2048);
         rvbuf[2047]='b';
         size = send(connfd, rvbuf, 2048, 0);
	 if(size>=0)
	 {
		printf("Data[%d] Sended:%c.\n",size,rvbuf[0]);
	 }
	 if(size==-1)
	 {
	    printf("Error[%d] when Sending Data:%s.\n",errno,strerror(errno));	 
            break;		
	 }
         sleep(1);
  }
   unix_socket_close(connfd);
   printf("Client exited.\n");    
 }

五、 討論

通過實際測試,發現UNIXDomain Socket與命名管道在表現上有很大的相似性,例如,UNIX Domain Socket也會在磁盤上創建一個socket類型文件;如果讀端進程關閉了,寫端進程“寫數據”時,有可能使進程異常退出,等等。查閱有關文檔,摘錄如下:

Send函數
當調用該函數時,send先比較待發送數據的長度len和套接字s的發送緩衝的 長度,如果len大於s的發送緩衝區的長度,該函數返回SOCKET_ERROR;如果len小於或者等於s的發送緩衝區的長度,那麼send先檢查協議是否正在發送s的發送緩衝中的數據,如果是就等待協議把數據發送完,如果協議還沒有開始發送s的發送緩衝中的數據或者s的發送緩衝中沒有數據,那麼 send就比較s的發送緩衝區的剩餘空間和len,如果len大於剩餘空間大小send就一直等待協議把s的發送緩衝中的數據發送完,如果len小於剩餘空間大小send就僅僅把buf中的數據copy到剩餘空間裏(注意並不是send把s的發送緩衝中的數據傳到連接的另一端的,而是協議傳的,send僅僅是把buf中的數據copy到s的發送緩衝區的剩餘空間裏)。如果send函數copy數據成功,就返回實際copy的字節數,如果send在copy數據時出現錯誤,那麼send就返回SOCKET_ERROR;如果send在等待協議傳送數據時網絡斷開的話,那麼send函數也返回SOCKET_ERROR。
要注意send函數把buf中的數據成功copy到s的發送緩衝的剩餘空間裏後它就返回了,但是此時這些數據並不一定馬上被傳到連接的另一端。如果協議在後續的傳送過程中出現網絡錯誤的話,那麼下一個Socket函數就會返回SOCKET_ERROR。(每一個除send外的Socket函數在執行的最開始總要先等待套接字的發送緩衝中的數據被協議傳送完畢才能繼續,如果在等待時出現網絡錯誤,那麼該Socket函數就返回 SOCKET_ERROR)
注意:在Unix系統下,如果send在等待協議傳送數據時網絡斷開的話,調用send的進程會接收到一個SIGPIPE信號,進程對該信號的默認處理是進程終止。

Recv函數與send類似,看樣子系統在實現各種IPC時,有些地方是複用的。

發佈了18 篇原創文章 · 獲贊 8 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章