命名管道(FIFO)特點
- 有路徑名,不相關進程也可通訊。
- 遵循先進先出,單向數據流。
- API:
mkfifo、open、read/write、close。
完整流程
- 父進程調用
mkfifo("/tmp/test_fifo", 0777) 創建管道文件。
fork() 創建子進程。
- 子進程
open(..., O_WRONLY),write() 寫入數據,close()。
- 父進程
wait() 等待子進程結束,再 open(..., O_RDONLY),read() 讀取,close()。
代碼示例
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
int main() {
char *fifo = "/tmp/test_fifo";
char input[] = "IPC by pipe";
char output[128];
pid_t pid;
int fd, n;
if (mkfifo(fifo, 0777) == -1) { perror("mkfifo"); exit(1); }
pid = fork();
if (pid > 0) { // 父進程
wait(NULL);
fd = open(fifo, O_RDONLY);
n = read(fd, output, sizeof(output)-1);
output[n] = '\0';
printf("父進程讀取 %d 字節: %s\n", n, output);
close(fd);
} else if (pid == 0) { // 子進程
fd = open(fifo, O_WRONLY);
n = write(fd, input, strlen(input));
printf("子進程寫入 %d 字節: %s\n", n, input);
close(fd);
} else { perror("fork"); exit(1); }
unlink(fifo);
return 0;
}
運行結果
父進程運行
子進程運行
子進程寫入 11 字節: IPC by pipe
父進程讀取 11 字節: IPC by pipe
關鍵點
- 父進程必須
wait() 確保子進程寫入完成再讀取,否則會阻塞或讀到空數據。
- 管道文件屬於文件系統,進程結束後需
unlink() 清理。