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

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值