因此,我正在使用 C 创建一个基本的 UNIX shell 项目的最后阶段。我已经完成了许多不同的程序部分,但现在我想征服管道。我特别想创建一个可以处理任意数量管道的程序。
出于某种原因,我的代码到达某行(标记为://DIES HERE)然后停止,我不知道为什么。
这是我到目前为止的代码:
//the contents of args[0] is {"ls","-l","-o"}
//the contents of args[1] is {"wc","-l"}
int pipefd[2];
pipe(&pipefd[0]); // Error check!
fflush(stdout);
for (i = 0; i < commands; i++){
int pid = fork();
if (pid == 0){
int command_no = i;
int prev_pipe = ((command_no - 1) % 2) * 2;
int current_pipe = (command_no % 2) * 2;
printf("\ncmd %d: prev pipe %d, curr pipe %d\n\n", i, prev_pipe, current_pipe);
fflush(stdout);
// If current command is the first command, close the
// read end, else read from the last command's pipe
if (command_no == 0){
close(pipefd[0]);
}
else{
dup2(pipefd[prev_pipe], 0);
close(pipefd[current_pipe]);
}
// If current command is the last command, close the
// write end, else write to the pipe
if (command_no == commands - 1){
close(pipefd[current_pipe + 1]);
}
else{
dup2(pipefd[current_pipe + 1], 1); //DIES HERE
}
// printf("Here?\n\n");
execvp(*args[i], args[i]);
fprintf(stderr, "Failed to exec: %s (%d: %s)\n", arrayOfCommands[i], errno, strerror(errno));
_exit(1);
}
}
任何帮助表示赞赏!:)