程序通訊--pipe管道
Linux函式原型
#include <unistd.h> int pipe(int filedes[2]);
filedes[0]用於讀出資料,讀取時必須關閉寫入端,即close(filedes[1]);
filedes[1]用於寫入資料,寫入時必須關閉讀取端,即close(filedes[0])。
程式例項:
#include <stdio.h> #include <unistd.h> #define MAXLINE20 int main(void) { int n; int fd[2]; pid_t pid; char line[MAXLINE]; if (pipe(fd) < 0) {/* 先建立管道得到一對檔案描述符 */ return -1; } if ((pid = fork()) < 0)/* 父程序把檔案描述符複製給子程序 */ return -2; else if(pid > 0) {/* 父程序寫 */ close(fd[0]);/* 關閉讀描述符 */ write(fd[1], "\nhello world\n", 14); } else {/* 子程序讀 */ close(fd[1]);/* 關閉寫端 */ n = read(fd[0], line, MAXLINE); write(STDOUT_FILENO, line, n); } return 0; }