管道是Unix中最古老的程序間通信的形式,我們把從一個程序連接配接到另一個程序的一個資料流稱為一個“管道”, 管道的本質是固定大小的核心緩沖區;
如:ps aux | grep httpd | awk '{print $2}'
管道限制
1)管道是半雙工的,資料隻能向一個方向流動;需要雙方通信時,需要建立起兩個管道;
2)匿名管道隻能用于具有共同祖先的程序(如父程序與fork出的子程序)之間進行通信, 原因是pipe建立的是兩個檔案描述符, 不同程序直接無法直接獲得;[通常,一個管道由一個程序建立,然後該程序調用fork,此後父子程序共享該管道]
建立一無名管道
參數
Pipefd:檔案描述符數組,其中pipefd[0]表示讀端,pipefd[1]表示寫端
管道建立示意圖

規則 1)管道空時
O_NONBLOCK disable:read調用阻塞,即程序暫停執行,一直等到有資料來到為止。
O_NONBLOCK enable:read調用傳回-1,errno值為EAGAIN。
規則 2)管道滿時
O_NONBLOCK disable: write調用阻塞,直到有程序讀走資料
O_NONBLOCK enable:調用傳回-1,errno值為EAGAIN
3)如果所有管道寫端對應的檔案描述符被關閉,則read傳回0
4)如果所有管道讀端對應的檔案描述符被關閉,則write操作會産生信号SIGPIPE
Linux PIPE特征
1)當要寫入的資料量不大于PIPE_BUF時,Linux将保證寫入的原子性。
2)當要寫入的資料量大于PIPE_BUF時,Linux将不再保證寫入的原子性。
man說明:
POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be atomic:
the output data is written to the pipe as a contiguous sequence.
Writes of more than PIPE_BUF bytes may be nonatomic:
the kernel may interleave the data with data written by other processes.
POSIX.1-2001 requires PIPE_BUF to be at least 512 bytes.
(On Linux, PIPE_BUF is 4096 bytes. 在Linux當中, PIPE_BUF為4位元組).
The precise semantics depend on whether the file descriptor is non-blocking(O_NONBLOCK),
whether there are multiple writers to the pipe, and on n, the number of bytes to be written:
O_NONBLOCK disabled(阻塞), n <= PIPE_BUF
All n bytes are written atomically; write(2) may block if there is not room for n bytes to be written immediately
O_NONBLOCK enabled(非阻塞), n <= PIPE_BUF
If there is room to write n bytes to the pipe, then write(2) succeeds immediately, writing all n bytes;
otherwise write(2) fails, with errno set to EAGAIN(注意: 如果空間不足以寫入資料, 則一個位元組也不寫入, 直接出錯傳回).
O_NONBLOCK disabled, n > PIPE_BUF
The write is nonatomic: the data given to write(2) may be interleaved with write(2)s by other process;
the write(2) blocks until n bytes have been written.
O_NONBLOCK enabled, n > PIPE_BUF
If the pipe is full, then write(2) fails, with errno set to EAGAIN(此時也是沒有一個字元寫入管道).
Otherwise, from 1 to n bytes may be written (i.e., a "partial write" may occur;
the caller should check the return value from write(2) to see how many bytes were actually written),
and these bytes may be interleaved with writes by other processes.
附-管道容量查詢
man 7 pipe
注意: 管道的容量不一定就等于PIPE_BUF, 如在Ubuntu中, 管道容量為64K, 而PIPE_BUF為4K.