首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言進程間通訊:命名管道(FIFO)實現父子進程數據傳輸

     編輯:關於C語言

命名管道(FIFO)特點

  • 有路徑名,不相關進程也可通訊。
  • 遵循先進先出,單向數據流。
  • API:mkfifo、open、read/write、close。

完整流程

  1. 父進程調用 mkfifo("/tmp/test_fifo", 0777) 創建管道文件。
  2. fork() 創建子進程。
  3. 子進程 open(..., O_WRONLY),write() 寫入數據,close()。
  4. 父進程 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() 清理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved