原文地址:
http://www.linuxgraphics.cn/gui/ipc_unix_socket.html,感謝原作者。
簡介
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 互相讀寫數
據。
其他參考網址:
IPC:Sockets
http://www.cs.cf.ac.uk/Dave/C/node28.html
Example Using UNIX Domain Stream Sockets
http://docs.hp.com/en/B2355-90136/ch06s07.html
重要參考資料:
《UNIX環境進階編程》第17章 17.3 Richard Stevens