UNIX domain socket怎么用(一)?

2020-03-03  本文已影响0人  _invincible_

概述

问题来源: 一个开源项目用这个当消息队列。
说明: 本文根据一个例子,查询Linux手册,介绍相关的概念先扫个盲。下一篇写一个完整的测试代码。

代码示例

#include <sys/socket.h>
#define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path)        \
                     + strlen ((ptr)->sun_path))

void * BindUnixDomain(char * path, int type, int max_msg_size){
    char * path;
    struct sockaddr_un n_us;
    int ossock = 0;

    memset(&n_us, 0, sizeof(n_us));
    n_us.sun_family = AF_UNIX;
    strncpy(n_us.sun_path, path, sizeof(n_us.sun_path) - 1);
    
    ossock = socket(PF_UNIX, type, 0);

    bind(ossock, (struct sockaddr *)&n_us, SUN_LEN(&n_us));
    
    chmod(path, 0660);
    
    listen(ossock, 128);

    // Set close-on-exec
    fcntl(ossock, F_SETFD, FD_CLOEXEC);
}

说明

相关函数: socket、bind、listen ...

#include <sys/socket.h>
#include <sys/un.h>
unix_socket = socket(AF_UNIX, type, 0);
error = socketpair(AF_UNIX, type, 0, int *sv);

#include <sys/types.h>         
#include <sys/socket.h>
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

什么是UNIX domain socket?

DESCRIPTION         

       The AF_UNIX (also known as AF_LOCAL) socket family is used to
       communicate between processes on the same machine efficiently.
       Traditionally, UNIX domain sockets can be either unnamed, or bound to
       a filesystem pathname (marked as being of type socket).  Linux also
       supports an abstract namespace which is independent of the
       filesystem.

为什么参数是SOCK_DGRAM用法跟网络socket一样吗?

DESCRIPTION         

       ...
       Valid socket types in the UNIX domain are: 
              SOCK_STREAM, for a stream-oriented socket; 
              SOCK_DGRAM, for a datagram-oriented socket that preserves message boundaries (as on most UNIX implementations, UNIX domain datagram sockets are always reliable and dont reorder datagrams); 
              and (since Linux 2.6.4) SOCK_SEQPACKET, for a sequenced-packet socket that is connection-oriented, preserves message boundaries, and delivers messages in the order that they were sent.
       ...

为什么AF_UNIX和PF_UNIX有什么区别?

NOTES         top
       POSIX.1 does not require the inclusion of <sys/types.h>, and this
       header file is not required on Linux.  However, some historical (BSD)
       implementations required this header file, and portable applications
       are probably wise to include it.

       The manifest constants used under 4.x BSD for protocol families are
       PF_UNIX, PF_INET, and so on, while AF_UNIX, AF_INET, and so on are
       used for address families.  However, already the BSD man page
       promises: "The protocol family generally is the same as the address
       family", and subsequent standards use AF_* everywhere.

结构体sockaddr_un是什么?

A UNIX domain socket address is represented in the following structure:

   struct sockaddr_un {
       sa_family_t sun_family;               /* AF_UNIX */
       char        sun_path[108];            /* Pathname */
   };
The sun_family field always contains AF_UNIX.  On Linux, sun_path is 108 bytes in size;

sun_path字段如何设置?


Three types of address are distinguished in the sockaddr_un structure:

       *  pathname: a UNIX domain socket can be bound to a null-terminated
          filesystem pathname using bind(2).  When the address of a pathname
          socket is returned (by one of the system calls noted above), its
          length is

              offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1

          and sun_path contains the null-terminated pathname.  (On Linux,
          the above offsetof() expression equates to the same value as
          sizeof(sa_family_t), but some other implementations include other
          fields before sun_path, so the offsetof() expression more portably
          describes the size of the address structure.)

       *  unnamed: A stream socket that has not been bound to a pathname
          using bind(2) has no name.  Likewise, the two sockets created by
          socketpair(2) are unnamed.  
          ...

       *  abstract: an abstract socket address is distinguished (from a
          pathname socket) by the fact that sun_path[0] is a null byte
          ('\0').  ...

Pathname sockets
       When binding a socket to a pathname, a few rules should be observed
       for maximum portability and ease of coding:

       *  The pathname in sun_path should be null-terminated.

       *  The length of the pathname, including the terminating null byte,
          should not exceed the size of sun_path.

SUN_LEN宏是干嘛的?


Pathname sockets
       ...
       *  The addrlen argument that describes the enclosing sockaddr_un
          structure should have a value of at least:

              offsetof(struct sockaddr_un, sun_path)+strlen(addr.sun_path)+1

          or, more simply, addrlen can be specified as sizeof(struct sock‐
          addr_un).

       There is some variation in how implementations handle UNIX domain
       socket addresses that do not follow the above rules.  For example,
       some (but not all) implementations append a null terminator if none
       is present in the supplied sun_path.

       When coding portable applications, keep in mind that some implementa‐
       tions have sun_path as short as 92 bytes.

       Various system calls (accept(2), recvfrom(2), getsockname(2),
       getpeername(2)) return socket address structures.  When applied to
       UNIX domain sockets, the value-result addrlen argument supplied to
       the call should be initialized as above.  Upon return, the argument
       is set to indicate the actual size of the address structure.  The
       caller should check the value returned in this argument: if the out‐
       put value exceeds the input value, then there is no guarantee that a
       null terminator is present in sun_path.  (See BUGS.)

绑定的文件能不能用cat等其他进程查看?

If the file already exists when we try to bind the same address,  the bind request will fail.
When we close the socket, this file is not automatically removed,  so we need to make sure that we unlink it before our application exits.

chmod的作用?

   Pathname socket ownership and permissions
       In the Linux implementation, pathname sockets honor the permissions
       of the directory they are in.  Creation of a new socket fails if the
       process does not have write and search (execute) permission on the
       directory in which the socket is created.

       On Linux, connecting to a stream socket object requires write permis‐
       sion on that socket; sending a datagram to a datagram socket likewise
       requires write permission on that socket.  POSIX does not make any
       statement about the effect of the permissions on a socket file, and
       on some systems (e.g., older BSDs), the socket permissions are
       ignored.  Portable programs should not rely on this feature for secu‐
       rity.

       When creating a new socket, the owner and group of the socket file
       are set according to the usual rules.  The socket file has all per‐
       missions enabled, other than those that are turned off by the process
       umask(2).

       The owner, group, and permissions of a pathname socket can be changed
       (using chown(2) and chmod(2)).

其他疑问

为什么用unix domain socket?
什么是socket family?
什么是POSIX, BSD?

参考资料

Linux Programmer's Manual UNIX(7)
Linux Programmer's Manual SOCKET(2)
Advanced Programming in the UNIX Environment 3rd Edition

上一篇 下一篇

猜你喜欢

热点阅读