管道 是 Linux 進程間通訊 (IPC) 最基礎機制。pipe() 建立單向資料流,需搭配 fork() 產生父子進程,一端寫入、一端讀取,遵循 FIFO 原則。本文詳細說明 pipe() 函式原型、回傳值、錯誤碼、完整父子進程通訊範例、非阻塞模式設定。

pipe() 建立,僅限親緣關係進程 (父子、兄弟),存在於記憶體,進程結束即消失。mkfifo() 建立檔案系統節點,任意進程可透過路徑開啟通訊,持久化存在。#include
int pipe(int filedes[2]);
// filedes[0] : 讀取端 (read end)
// filedes[1] : 寫入端 (write end)
// 成功返回 0,失敗 -1 (errno: EMFILE, ENFILE, EFAULT)
#include
#include
#include
#include
int main(void) {
int filedes[2];
char buf[80];
pid_t pid;
if (pipe(filedes) < 0) {
perror("pipe");
return 1;
}
pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid > 0) { // 父進程
close(filedes[0]); // 關閉讀取端
const char *msg = "Hello world, this is write by pipe.\n";
write(filedes[1], msg, strlen(msg));
close(filedes[1]); // 關閉寫入端 → 觸發讀取端 EOF
waitpid(pid, NULL, 0);
} else { // 子進程
close(filedes[1]); // 關閉寫入端
read(filedes[0], buf, sizeof(buf));
printf("Child read: %s", buf);
close(filedes[0]);
}
return 0;
}
[root@localhost src]# gcc pipe.c
[root@localhost src]# ./a.out
Child read: Hello world, this is write by pipe.
read() 阻塞;管道滿 (預設 64KB) 時 write() 阻塞。#include
fcntl(filedes[0], F_SETFL, O_NONBLOCK); // 讀取端非阻塞
fcntl(filedes[1], F_SETFL, O_NONBLOCK); // 寫入端非阻塞
// read() 無資料時返回 -1, errno=EAGAIN
// write() 管道滿時返回 -1, errno=EAGAIN
建立兩個管道:pipe(fd1) 父→子,pipe(fd2) 子→父。
// Shell
mkfifo /tmp/myfifo
# 程式中
int fd = open("/tmp/myfifo", O_RDONLY); // 或 O_WRONLY
// 後續 read/write 同無名管道
管道是 Linux IPC 基石,掌握 pipe() + fork() 核心模式,即可構建高效進程協作程式。