您的位置:首页 > 大数据 > 人工智能

/LGC设计模式/进程间通信之 Unix Domain Socket

2010-12-28 12:44 465 查看
进程间通信之 Unix Domain Socket

作者:
刘鹏

日期:

2008-10-20

本文介绍了 Unix Domaiin Socket 这种进程间通信方式,详细描述了具体流程、函数接口,并给出了示例代码。

简介

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。

示例代码

socket.tar.gz
该代码实现了两个进程用 Unix Domain Socket 互相读写数
据。

See Also

MiniGUI 进程版体系结构

深入分析 select 的使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: