管道的五個特點:
(1)單向通信,資料只能從一個進程流向另一個進程;要雙工就得建兩個管道。
(2)只能用於有血緣關係的進程之間。
(3)流式服務,傳送與接收大小不受特定格式限制。
(4)生命週期與進程相關。
(5)遵循同步與互斥原則。
要改變已開啟檔案的性質,可以用 fcntl():
F_GETFL 取得檔案描述符狀態旗標,此旗標即 open() 的參數 flags。
F_SETFL 設定狀態旗標,參數 arg 為新旗標,但只允許改動 O_APPEND、O_NONBLOCK 與 O_ASYNC 這幾位,其他位不受影響。
下面的程式把寫端設為非阻塞,一路寫入直到 write 失敗,就能量出管道到底能裝多少:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int _pipe[2];
if (pipe(_pipe) == -1)
{
printf("pipe error\n");
return 1;
}
int ret;
int count = 0;
int flag = fcntl(_pipe[1], F_GETFL);
fcntl(_pipe[1], F_SETFL, flag | O_NONBLOCK);
while (1)
{
ret = write(_pipe[1], "A", 1);
if (ret == -1)
{
printf("error %s\n", strerror(errno));
break;
}
count++;
}
printf("count=%d\n", count);
return 0;
}
由此可見,管道的容量是 64KB。