Moakap總結
函數
#include <unistd.h>
int pipe(int filedes[2]);
描述
pipe()函數創建一個管道和指向該管道的一對文件描述符,並且將文件描述符存儲到文件描述符數組filedes[]中。其中filedes[0]為讀端,filedes[1]為寫端。
返回值
0 – 管道創建成功;
-1 – 管道創建失敗,同時errno置位;
錯誤指示
EFAULT – 無效的輸入參數filedes;
EMFILE – 達到當前進程允許的文件描述符最大值;
ENFILE – 達到系統允許的打開文件的最大數;
實例
下邊的例子首先創建一個管道,然後通過fork()創建當先進程的子進程。接著每個進程關閉讀寫管道不需要的文件描述符。子進程在當前路徑下執行“ls –a”命令,通過將管道寫描述符fd[1]復制成標准輸出,將命令執行輸出寫到管道;父進程通過fd[0]讀取管道數據並顯示。
#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 fd[2];
pid_t pid;
char read_buffer[500] = {0};
int read_count = 0;
int status = 0;
//創建管道
if (pipe(fd) < 0)
{
printf("Create pipe failed.");
return -1;
}
//創建子進程
if ((pid = fork()) < 0)
{
printf("Fork failed.");
return -1;
}
//子進程操作
if (pid == 0)
{
printf("[child]Close read endpoint...");
close(fd[0]); /* 關閉不使用的讀 文件描述符 */
//復制fd[1]到標准輸出
if (fd[1] != STDOUT_FILENO)
{
if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
{
return -1;
}
//close fd[1],標准輸出即為fd[1]
close(fd[1]);
}
//執行命令
status = system("ls –a");
if (status == -1)
{
return -1;
}
}
else
{
printf("[parent]Close write endpoint...");
//父進程 讀 操作
close(fd[1]); /* 關閉不使用的寫 文件描述符 */
//從管道讀數據
read_count = read(fd[0], read_buffer, 500);
printf("Content under current directory: \n%s", read_buffer);
}
}