您的位置:首页 > 理论基础 > 计算机网络

UNIX网络编程卷一:第十五章 Unix域套接字

2015-08-12 14:58 459 查看
Unix域协议

它并不是一个实际的协议族,而是在单个主机上执行客户/服务器通信的一种方法.

在UNPvol2--IPC(进程间通信)中,Unix域协议可以当作一种IPC方法.

Unix域提供两类套接字:

1) 字节流套接字 (类似TCP)

2) 数据报套接字 (类似UDP)

为什么使用Unix域套接字?

1) 当通信两端位于同一主机上时,Unix域套接字要快.

2) 可用于在同一主机上不同进程间传递描述符.

3) 它把客户凭证(用户ID和组ID)提供给服务器,从而提供额外的安全检查.

Unix域中使用 文件系统中的路径名 来标识客户和服务器的协议地址.

(在单个主机上嘛,使用路径名就可以了)

但是这些路径名不是普通的Unix文件,除非把他们和Unix域套接字关联起来,否则无法读写这些文件.

查看Unix域的帮助

$ man 7 unix

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 filesys‐
       tem.

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

       UNIX domain sockets support passing file descriptors or process credentials to other processes using ancillary data.


地址结构

struct sockaddr_un {
sa_family_t sun_family;               /* AF_UNIX */
char        sun_path[UNIX_PATH_MAX];  /* pathname */
};


描述符传递


1)有亲缘关系的进程:

fork 调用返回后,子进程共享父进程的所有打开的描述符

exec 调用执行后,所有描述符通常保持打开状态不变。

2)  无亲缘关系的进程:

首先在这两个进程之间创建一个Unix域套接字,

然后使用sendmsg跨这个套接字发送一个特殊消息. 这个消息由内核来专门处理, 会把打开的描述符从发送进程传递到接收进程.



总结:



代码地址:https://github.com/huntinux/unpvol1/tree/master/15chp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: