pipe() - Unix,Linux系統呼叫 - 技術教學
Tutorials Point


  Unix入門
  Unix Shell程式設計
  高階Unix
  Unix有用參考
  Unix有用資源
  精選閱讀

版權所有 © 2014 tutorialspoint



  首頁     參考資料     討論區     關於TP  

pipe() - Unix,Linux系統呼叫


previous next AddThis Social Bookmark Button

廣告

名稱

pipe - 建立管道

概要

#include <unistd.h>

int pipe(int filedes[2]);

描述

pipe() 建立一對指向管道inode的檔案描述符,並將它們放置在filedes指向的陣列中。filedes[0]用於讀取,filedes[1]用於寫入。

返回值

成功時返回零。出錯時返回 -1,並適當地設定errno

錯誤

標籤描述
EFAULT filedes無效。
EMFILE 程序使用了過多的檔案描述符。
ENFILE 已達到系統對開啟檔案總數的限制。

符合標準

POSIX.1-2001。

示例

下面的程式建立一個管道,然後使用fork(2)建立一個子程序。fork(2)之後,每個程序都關閉它不需要的管道描述符(參見pipe(7))。然後父程序將程式命令列引數中包含的字串寫入管道,子程序一次讀取一個位元組地從管道讀取此字串,並在標準輸出上將其回顯。

#include <sys/wait.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h>

int main(int argc, char *argv[]) { int pfd[2]; pid_t cpid; char buf;

assert(argc == 2);

if (pipe(pfd) == -1) { perror("pipe"); exit(EXIT_FAILURE); }

cpid = fork(); if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); }

if (cpid == 0) { /* Child reads from pipe */ close(pfd[1]); /* Close unused write end */

while (read(pfd[0], &buf, 1) > 0) write(STDOUT_FILENO, &buf, 1);

write(STDOUT_FILENO, "\n", 1); close(pfd[0]); _exit(EXIT_SUCCESS);

} else { /* Parent writes argv[1] to pipe */ close(pfd[0]); /* Close unused read end */ write(pfd[1], argv[1], strlen(argv[1])); close(pfd[1]); /* Reader will see EOF */ wait(NULL); /* Wait for child */ exit(EXIT_SUCCESS); } }

參見



previous next Printer Friendly

廣告


  

廣告



廣告
© . All rights reserved.