unix domain socket介绍

来源:互联网 发布:java类的生命周期 编辑:程序博客网 时间:2024/04/19 17:10

 首先使用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。

原创粉丝点击