Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5467018
  • 博文数量: 922
  • 博客积分: 19333
  • 博客等级: 上将
  • 技术积分: 11226
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-27 14:33
文章分类

全部博文(922)

文章存档

2023年(1)

2020年(2)

2019年(1)

2017年(1)

2016年(3)

2015年(10)

2014年(17)

2013年(49)

2012年(291)

2011年(266)

2010年(95)

2009年(54)

2008年(132)

分类: LINUX

2014-11-07 21:08:45

进程间通信之 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。

示例代码

  •  该代码实现了两个进程用 Unix Domain Socket 互相读写数 据。
阅读(2006) | 评论(0) | 转发(0) |
0

上一篇:Linux下的IPC-UNIX Domain Socket

下一篇:绝对

给主人留下些什么吧!~~