Socket編程實踐(13) --UNIX域協議

UNIX域協議

   UNIX域套接字與TCP相比, 在同一臺主機上, UNIX域套接字更有效率, 幾乎是TCP的兩倍(由於UNIX域套接字不需要經過網絡協議棧,不需要打包/拆包,計算校驗和,維護序號和應答等,只是將應用層數據從一個進程拷貝到另一個進程, 而且UNIX域協議機制本質上就是可靠的通訊, 而網絡協議是爲不可靠的通訊設計的).

   UNIX域套接字可以在同一臺主機上各進程之間傳遞文件描述符;

   UNIX域套接字與傳統套接字的區別是用路徑名來表示協議族的描述;

   UNIX域套接字也提供面向流和麪向數據包兩種API接口,類似於TCP和UDP,但是面向消息的UNIX套接字也是可靠的,消息既不會丟失也不會順序錯亂。

   使用UNIX域套接字的過程和網絡socket十分相似, 也要先調用socket創建一個socket文件描述符, family指定爲AF_UNIX, type可以選擇SOCK_DGRAM/SOCK_STREAM;

 

UNIX域套接字地址結構:

  1. #define UNIX_PATH_MAX    108  
  2. struct sockaddr_un  
  3. {  
  4.     sa_family_t sun_family;               /* AF_UNIX */  
  5.     char        sun_path[UNIX_PATH_MAX];  /* pathname */  
  6. };  

基於UNIX域套接字的echo-server/client程序

  1. /**Server端**/  
  2. void echoServer(int sockfd);  
  3. int main()  
  4. {  
  5.     signal(SIGCHLD, sigHandlerForSigChild);  
  6.     int listenfd = socket(AF_UNIX, SOCK_STREAM, 0);  
  7.     if (listenfd == -1)  
  8.         err_exit("socket error");  
  9.   
  10.     char pathname[] = "/tmp/test_for_unix";  
  11.     unlink(pathname);  
  12.     struct sockaddr_un servAddr;  
  13.     servAddr.sun_family = AF_UNIX;  
  14.     strcpy(servAddr.sun_path, pathname);  
  15.     if (bind(listenfd, (struct sockaddr *)&servAddr, sizeof(servAddr)) == -1)  
  16.         err_exit("bind error");  
  17.     if (listen(listenfd, 128) == -1)  
  18.         err_exit("listen error");  
  19.   
  20.     while (true)  
  21.     {  
  22.         int connfd = accept(listenfd, NULL, NULL);  
  23.         if (connfd == -1)  
  24.             err_exit("accept error");  
  25.   
  26.         pid_t pid = fork();  
  27.         if (pid == -1)  
  28.             err_exit("fork error");  
  29.         else if (pid > 0)  
  30.             close(connfd);  
  31.         else if (pid == 0)  
  32.         {  
  33.             close(listenfd);  
  34.             echoServer(connfd);  
  35.             close(connfd);  
  36.             exit(EXIT_SUCCESS);  
  37.         }  
  38.     }  
  39. }  
  40. void echoServer(int sockfd)  
  41. {  
  42.     char buf[BUFSIZ];  
  43.     while (true)  
  44.     {  
  45.         memset(buf, 0, sizeof(buf));  
  46.         int recvBytes = read(sockfd, buf, sizeof(buf));  
  47.         if (recvBytes < 0)  
  48.         {  
  49.             if (errno == EINTR)  
  50.                 continue;  
  51.             else  
  52.                 err_exit("read socket error");  
  53.         }  
  54.         else if (recvBytes == 0)  
  55.         {  
  56.             cout << "client connect closed..." << endl;  
  57.             break;  
  58.         }  
  59.   
  60.         cout << buf ;  
  61.         if (write(sockfd, buf, recvBytes) == -1)  
  62.             err_exit("write socket error");  
  63.     }  
  64. }  
  1. /**Client端代碼**/  
  2. void echoClient(int sockfd);  
  3. int main()  
  4. {  
  5.     int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);  
  6.     if (sockfd == -1)  
  7.         err_exit("socket error");  
  8.   
  9.     char pathname[] = "/tmp/test_for_unix";  
  10.     struct sockaddr_un servAddr;  
  11.     servAddr.sun_family = AF_UNIX;  
  12.     strcpy(servAddr.sun_path, pathname);  
  13.     if (connect(sockfd, (struct sockaddr *)&servAddr, sizeof(servAddr)) == -1)  
  14.         err_exit("connect error");  
  15.   
  16.     echoClient(sockfd);  
  17. }  
  18. void echoClient(int sockfd)  
  19. {  
  20.     char buf[BUFSIZ] = {0};  
  21.     while (fgets(buf, sizeof(buf), stdin) != NULL)  
  22.     {  
  23.         if (write(sockfd, buf, strlen(buf)) == -1)  
  24.             err_exit("write socket error");  
  25.         memset(buf, 0, sizeof(buf));  
  26.         int recvBytes = read(sockfd, buf, sizeof(buf));  
  27.         if (recvBytes == -1)  
  28.         {  
  29.             if (errno == EINTR)  
  30.                 continue;  
  31.             else  
  32.                 err_exit("read socket error");  
  33.         }  
  34.         cout << buf ;  
  35.         memset(buf, 0, sizeof(buf));  
  36.     }  
  37. }  

UNIX域套接字編程注意點

   1.bind成功將會創建一個文件,權限爲0777 & ~umask

   2.sun_path最好用一個/tmp目錄下的文件的絕對路徑, 而且server端在指定該文件之前首先要unlink一下;

   3.UNIX域協議支持流式套接口(需要處理粘包問題)與報式套接口(基於數據報)

   4.UNIX域流式套接字connect發現監聽隊列滿時,會立刻返回一個ECONNREFUSED,這和TCP不同,如果監聽隊列滿,會忽略到來的SYN,這導致對方重傳SYN。

 

傳遞文件描述符

socketpair

  1. #include <sys/types.h>  
  2. #include <sys/socket.h>  
  3. int socketpair(int domain, int type, int protocol, int sv[2]);  

創建一個全雙工的流管道

參數:

   domain: 協議家族, 可以使用AF_UNIX(AF_LOCAL)UNIX域協議, 而且在Linux上, 該函數也就只支持這一種協議;

   type: 套接字類型, 可以使用SOCK_STREAM

   protocol: 協議類型, 一般填充爲0;

   sv: 返回的套接字對;

socketpair 函數跟pipe 函數是類似: 只能在具有親緣關係的進程間通信,但pipe 創建的匿名管道是半雙工的,而socketpair 可以認爲是創建一個全雙工的管道。

可以使用socketpair 創建返回的套接字對進行父子進程通信, 如下例:

  1. int main()  
  2. {  
  3.     int sockfds[2];  
  4.     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfds) == -1)  
  5.         err_exit("socketpair error");  
  6.   
  7.     pid_t pid = fork();  
  8.     if (pid == -1)  
  9.         err_exit("fork error");  
  10.     // 父進程, 只負責數據的打印  
  11.     else if (pid > 0)  
  12.     {  
  13.         close(sockfds[1]);  
  14.         int iVal = 0;  
  15.         while (true)  
  16.         {  
  17.             cout << "value = " << iVal << endl;  
  18.             write(sockfds[0], &iVal, sizeof(iVal));  
  19.             read(sockfds[0], &iVal, sizeof(iVal));  
  20.             sleep(1);  
  21.         }  
  22.     }  
  23.     // 子進程, 只負責數據的更改(+1)  
  24.     else if (pid == 0)  
  25.     {  
  26.         close(sockfds[0]);  
  27.         int iVal = 0;  
  28.         while (read(sockfds[1], &iVal, sizeof(iVal)) > 0)  
  29.         {  
  30.             ++ iVal;  
  31.             write(sockfds[1], &iVal, sizeof(iVal));  
  32.         }  
  33.     }  
  34. }  

sendmsg/recvmsg

  1. #include <sys/types.h>  
  2. #include <sys/socket.h>  
  3. ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);  
  4. ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);  

它們與sendto/send 和 recvfrom/recv 函數類似,只不過可以傳輸更復雜的數據結構,不僅可以傳輸一般數據,還可以傳輸額外的數據,如文件描述符。

  1. //msghdr結構體  
  2. struct msghdr  
  3. {  
  4.     void         *msg_name;       /* optional address */  
  5.     socklen_t     msg_namelen;    /* size of address */  
  6.     struct iovec *msg_iov;        /* scatter/gather array */  
  7.     size_t        msg_iovlen;     /* # elements in msg_iov */  
  8.     void         *msg_control;    /* ancillary data, see below */  
  9.     size_t        msg_controllen; /* ancillary data buffer len */  
  10.     int           msg_flags;      /* flags on received message */  
  11. };  
  12. struct iovec                      /* Scatter/gather array items */  
  13. {  
  14.     void  *iov_base;              /* Starting address */  
  15.     size_t iov_len;               /* Number of bytes to transfer */  
  16. };  

msghdr結構體成員解釋:

   1)msg_name :即對等方的地址指針,不關心時設爲NULL即可;

   2)msg_namelen:地址長度,不關心時設置爲0即可;

   3)msg_iov:是結構體iovec 的指針, 指向需要發送的普通數據, 見下圖。   

      成員iov_base 可以認爲是傳輸正常數據時的buf;

      成員iov_len 是buf 的大小;

   4)msg_iovlen:當有n個iovec 結構體時,此值爲n;

   5)msg_control:是一個指向cmsghdr 結構體的指針(見下圖), 當需要發送輔助數據(如控制信息/文件描述符)時, 需要設置該字段, 當發送正常數據時, 就不需要關心該字段, 並且msg_controllen可以置爲0;

   6)msg_controllen:cmsghdr 結構體可能不止一個(見下圖):

   7)flags: 不用關心;


  1. //cmsghdr結構體  
  2. struct cmsghdr  
  3. {  
  4.     socklen_t cmsg_len;    /* data byte count, including header */  
  5.     int       cmsg_level;  /* originating protocol */  
  6.     int       cmsg_type;   /* protocol-specific type */  
  7.     /* followed by unsigned char cmsg_data[]; */  
  8. };  

爲了對齊,可能存在一些填充字節(見下圖),跟系統的實現有關,但我們不必關心,可以通過一些函數宏來獲取相關的值,如下:

  1. #include <sys/socket.h>  
  2. struct cmsghdr *CMSG_FIRSTHDR(struct msghdr *msgh);   
  3. //獲取輔助數據的第一條消息  
  4. struct cmsghdr *CMSG_NXTHDR(struct msghdr *msgh, struct cmsghdr *cmsg); //獲取輔助數據的下一條信息  
  5. size_t CMSG_ALIGN(size_t length);     
  6. size_t CMSG_SPACE(size_t length);  
  7. size_t CMSG_LEN(size_t length); //length使用的是的(實際)數據的長度, 見下圖(兩條填充數據的中間部分)  
  8. unsigned char *CMSG_DATA(struct cmsghdr *cmsg);  


進程間傳遞文件描述符

  1. /**示例: 封裝兩個函數send_fd/recv_fd用於在進程間傳遞文件描述符**/  
  2. int send_fd(int sockfd, int sendfd)  
  3. {  
  4.     // 填充 name 字段  
  5.     struct msghdr msg;  
  6.     msg.msg_name = NULL;  
  7.     msg.msg_namelen = 0;  
  8.   
  9.     // 填充 iov 字段  
  10.     struct iovec iov;  
  11.     char sendchar = '\0';  
  12.     iov.iov_base = &sendchar;  
  13.     iov.iov_len = 1;  
  14.     msg.msg_iov = &iov;  
  15.     msg.msg_iovlen = 1;  
  16.   
  17.     // 填充 cmsg 字段  
  18.     struct cmsghdr cmsg;  
  19.     cmsg.cmsg_len = CMSG_LEN(sizeof(int));  
  20.     cmsg.cmsg_level = SOL_SOCKET;  
  21.     cmsg.cmsg_type = SCM_RIGHTS;  
  22.     *(int *)CMSG_DATA(&cmsg) = sendfd;  
  23.     msg.msg_control = &cmsg;  
  24.     msg.msg_controllen = CMSG_LEN(sizeof(int));  
  25.   
  26.     // 發送  
  27.     if (sendmsg(sockfd, &msg, 0) == -1)  
  28.         return -1;  
  29.     return 0;  
  30. }  
  1. int recv_fd(int sockfd)  
  2. {  
  3.     // 填充 name 字段  
  4.     struct msghdr msg;  
  5.     msg.msg_name = NULL;  
  6.     msg.msg_namelen = 0;  
  7.   
  8.     // 填充 iov 字段  
  9.     struct iovec iov;  
  10.     char recvchar;  
  11.     iov.iov_base = &recvchar;  
  12.     iov.iov_len = 1;  
  13.     msg.msg_iov = &iov;  
  14.     msg.msg_iovlen = 1;  
  15.   
  16.     // 填充 cmsg 字段  
  17.     struct cmsghdr cmsg;  
  18.     msg.msg_control = &cmsg;  
  19.     msg.msg_controllen = CMSG_LEN(sizeof(int));  
  20.   
  21.     // 接收  
  22.     if (recvmsg(sockfd, &msg, 0) == -1)  
  23.         return -1;  
  24.     return *(int *)CMSG_DATA(&cmsg);  
  25. }  
  1. int main()  
  2. {  
  3.     int sockfds[2];  
  4.     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfds) == -1)  
  5.         err_exit("socketpair error");  
  6.   
  7.     pid_t pid = fork();  
  8.     if (pid == -1)  
  9.         err_exit("fork error");  
  10.     // 子進程以只讀方式打開文件, 將文件描述符發送給子進程  
  11.     else if (pid ==  0)  
  12.     {  
  13.         close(sockfds[1]);  
  14.         int fd = open("read.txt", O_RDONLY);  
  15.         if (fd == -1)  
  16.             err_exit("open error");  
  17.         cout << "In child,  fd = " << fd << endl;  
  18.         send_fd(sockfds[0], fd);  
  19.     }  
  20.     // 父進程從文件描述符中讀取數據  
  21.     else if (pid > 0)  
  22.     {  
  23.         close(sockfds[0]);  
  24.         int fd = recv_fd(sockfds[1]);  
  25.         if (fd == -1)  
  26.             err_exit("recv_fd error");  
  27.         cout << "In parent, fd = " << fd << endl;  
  28.   
  29.         char buf[BUFSIZ] = {0};  
  30.         int readBytes = read(fd, buf, sizeof(buf));  
  31.         if (readBytes == -1)  
  32.             err_exit("read fd error");  
  33.         cout << buf;  
  34.     }  
  35. }  

分析:

   我們知道,父進程在fork 之前打開的文件描述符,子進程是可以共享的,但是子進程打開的文件描述符,父進程是不能共享的,上述程序就是舉例在子進程中打開了一個文件描述符,然後通過send_fd 函數將文件描述符傳遞給父進程,父進程可以通過recv_fd 函數接收到這個文件描述符。先建立一個文件read.txt 後輸入幾個字符,然後運行程序;

 

注意:

   (1)只有UNIX域協議才能在本機進程間傳遞文件描述符;

   (2)進程間傳遞文件描述符並不是傳遞文件描述符的值(其實send_fd/recv_fd的兩個值也是不同的), 而是要在接收進程中創建一個新的文件描述符, 並且該文件描述符和發送進程中被傳遞的文件描述符指向內核中相同的文件表項.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章