2 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
這里沒有什么復(fù)雜的,只要記住最后一個(gè)命令應(yīng)該輸出到原始進(jìn)程'文件描述符1,第一個(gè)應(yīng)該從原始進(jìn)程文件描述符0讀取。你只是按順序生成進(jìn)程,沿著輸入端傳輸previois pipe
電話。
所以,以下是類型:
#include <unistd.h>struct command{ const char **argv;};
使用簡(jiǎn)單明確定義的語義創(chuàng)建一個(gè)輔助函數(shù):
intspawn_proc (int in, int out, struct command *cmd){ pid_t pid; if ((pid = fork ()) == 0) { if (in != 0) { dup2 (in, 0); close (in); } if (out != 1) { dup2 (out, 1); close (out); } return execvp (cmd->argv [0], (char * const *)cmd->argv); } return pid;}
這是主叉例程:
intfork_pipes (int n, struct command *cmd){ int i; pid_t pid; int in, fd [2]; /* The first process should get its input from the original file descriptor 0. */ in = 0; /* Note the loop bound, we spawn here all, but the last stage of the pipeline. */ for (i = 0; i < n - 1; ++i) { pipe (fd); /* f [1] is the write end of the pipe, we carry `in` from the prev iteration. */ spawn_proc (in, fd [1], cmd + i); /* No need for the write end of the pipe, the child will write here. */ close (fd [1]); /* Keep the read end of the pipe, the next child will read from there. */ in = fd [0]; } /* Last stage of the pipeline - set stdin be the read end of the previous pipe and output to the original file descriptor 1. */ if (in != 0) dup2 (in, 0); /* Execute the last stage with the current process. */ return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);}
還有一個(gè)小測(cè)試:
intmain (){ const char *ls[] = { "ls", "-l", 0 }; const char *awk[] = { "awk", "{print $1}", 0 }; const char *sort[] = { "sort", 0 }; const char *uniq[] = { "uniq", 0 }; struct command cmd [] = { {ls}, {awk}, {sort}, {uniq} }; return fork_pipes (4, cmd);}
似乎工作。:)

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
首先,你過早地關(guān)閉管道。僅關(guān)閉當(dāng)前進(jìn)程中不需要的結(jié)尾,并記住關(guān)閉子進(jìn)程中的stdin / stdout。
其次,您需要記住上一個(gè)命令中的fd。因此,對(duì)于兩個(gè)進(jìn)程,這看起來像:
int pipe[2];pipe(pipe);if ( fork() == 0 ) { /* Redirect output of process into pipe */ close(stdout); close(pipe[0]); dup2( pipe[1], stdout ); execvp(commands[0].argv[0], &commands[0].argv[0]);} if ( fork() == 0 ) { /* Redirect input of process out of pipe */ close(stdin); close(pipe[1]); dup2( pipe[0], stdin ); execvp(commands[1].argv[0], &commands[1].argv[0]);}/* Main process */close( pipe[0] );close( pipe[1] );waitpid();
現(xiàn)在你的工作是為此添加錯(cuò)誤處理并為n個(gè)進(jìn)程生成n-1個(gè)管道。第一個(gè)fork()塊中的代碼需要為進(jìn)程1..n-1的相應(yīng)管道運(yùn)行,而第二個(gè)fork()塊中的代碼用于進(jìn)程2..n。
- 2 回答
- 0 關(guān)注
- 537 瀏覽
添加回答
舉報(bào)