unix domain socket介绍

 首先使用unix domain socket有三个好处:
1)在同一主机上,unix domain socket比一般的tcp socket快上一倍,性能因素这是一个主要原因。
2)unix domain socket可以在同一主机的不同进程之间传递文件描述符
3)较新的unix domain socket实现把客户的ID和组ID提供给服务器,可以让服务器作安全检查。

 

GUI 系统中本机的客户/服务器结构通常基于 Unix Domain Socket 来实现。如X window 系统中,X11 客户在连接到 X11 服务器之前,首先根据 Display 等环境变量的设置来判断 X11 服务器所在的主机,如果主机是同一台主机,则会使用 UNIX Domain Socket 连接到服务器。

Unix Domain Socket 基本流程

利用 Unix Domain Socket 进行通信的基本流程如下图所示:

socket

socket() creates an endpoint for communication and returns a descriptor.

bind

bind() gives the socket sockfd the local address my_addr. It is normally necessary to assign a local address using bind() before a SOCK_STREAM socket may receive connections.

listen

To accept connections, a socket is first created with socket (), a willingness to accept incoming connections and a queue limit for incoming connections are specified with listen(), and then the connections are accepted with accept. The listen() call applies only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

accept

The accept() system call is used with connection-based socket types (SOCK_STREAM, SOCK_SEQPACKET). It extracts the first connection request on the queue of pending connections, creates a new connected socket, and returns a new file descriptor referring to that socket.

connect

The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by serv_addr.

read 和 write

相互通信的两个进程建立连接后,通过函数 read 和 write 完成数据的读写。

在读与写的两个进程之间,操作系统内核提供了一个数据缓冲区;调用 write 函数写数据时,数据被写入数据缓冲区;调用 read 函数读数据时,从缓冲区读取数据。当缓冲区空时,read 函数将等待,直到缓冲区有数据为止。当缓冲区满时,write 函数等待,直到缓冲区有空闲空间为止。

与 select 配合使用

Unix Domain Socket 编程经常与 select 配合使用,select 函数负责监听套接字,当有连接请求或者现有连接有数据要读写时,调用 accept 函数接受连接请求并建立连接,调用 read/write 完成数据读写。

通过使用 fdsets 及其接口可实现 select 对多个文件描述符的监听,select 返回处于 ready 状态的文件描述符个数,通过 FD_ISSET 接口判断某个文件描述符是否 ready。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值