Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux管理 >> Linux維護

Linux 建立 pipe 管道函式的做法與注意事項

管道是行程間通訊最古老也最方便的方式,而它的核心就是 pipe() 這個系統呼叫。Linux 的管道分為無名與命名兩類,用途不同。

無名管道

主要用於父子行程或兄弟行程之間。它由父行程建立,是單向的;若需要雙向通訊,就得開兩條管道。管道兩端的行程都把它當成檔案看待,一端寫、一端讀,資料遵循先入先出(FIFO)規則。

命名管道

為了解決無名管道只能「近親通訊」的限制,命名管道被設計出來。它是存在於檔案系統上、有自己名字的 FIFO 檔案,任何行程都能在任意時間透過檔名與它建立關係。雖然 inode 在磁碟上,實際資料仍舊存在記憶體緩衝頁面中,讀寫語法則與普通管道完全相同。

函式說明

#include <unistd.h>
int pipe(int filedes[2]);

pipe() 會建立管道,並把兩個檔案描述詞透過參數陣列回傳:filedes[0] 是讀取端,filedes[1] 是寫入端。成功回傳 0,失敗回傳 -1 並設定 errno。

常見錯誤碼:EMFILE 行程已用完可配檔案描述詞上限;ENFILE 系統已無可用的檔案描述詞;EFAULT 傳入的陣列位址不合法。

實作範例

#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>

int main(void)
{
  int filedes[2];
  char buf[80];
  pid_t pid;
  pipe(filedes);
  pid = fork();
  if (pid > 0)
  {
    printf("This is in the father process, here write a string to the pipe.\n");
    char s[] = "Hello world, this is write by pipe.\n";
    write(filedes[1], s, sizeof(s));
    close(filedes[0]);
    close(filedes[1]);
  }
  else if (pid == 0)
  {
    printf("This is in the child process, here read a string from the pipe.\n");
    read(filedes[0], buf, sizeof(buf));
    printf("%s\n", buf);
    close(filedes[0]);
    close(filedes[1]);
  }
  waitpid(pid, NULL, 0);
  return 0;
}

編譯執行:

[root@localhost src]# gcc pipe.c
[root@localhost src]# ./a.out
This is in the child process, here read a string from the pipe.
This is in the father process, here write a string to the pipe.
Hello world, this is write by pipe.

資料被讀完後管道即為空,隨後的 read() 預設會被阻住等待新資料。若要改為非阻塞:

fcntl(filedes[0], F_SETFL, O_NONBLOCK);
fcntl(filedes[1], F_SETFL, O_NONBLOCK);

最後牢記一件事:pipe() 必須與 fork() 搭配使用,父子行程共享同一組描述詞,否則根本達不到行程間通訊的目的。

Copyright © Linux教程網 All Rights Reserved