このウェブサイトから入手したチュートリアルを使用して、複数のパイプを実装しようとしています。複数のパイプを処理する関数を実行した後、不適切なファイル記述子エラーが発生するようです。初めて複製すると、このエラーが表示されます。コードは次のとおりです。
void runPipedCommands(cmdLine* command, char* userInput) {
int numPipes = countPipes(userInput);
int status = 0;
int i = 0, j = 0;
pid_t pid;
int pipefds[2*numPipes];
for(i = 0; i < (numPipes); i++){
if(pipe(pipefds + i*2) < 0) {
perror("pipe");
exit(EXIT_FAILURE);
}
}
j = 0;
while(command) {
pid = fork();
if(pid == 0) {
//if not first command
if(j != 0){
if(dup2(pipefds[j-2], 0) < 0){
perror(" dup2");///j-2 0 j+1 1
exit(EXIT_FAILURE);
}
if(command->next){
printf(
if(dup2(pipefds[j + 1], 1) < 0){
perror("dup2");
exit(EXIT_FAILURE);
}
}
for(i = 0; i < 2*numPipes; i++){
close(pipefds[i]);
}
if( execvp(*command->arguments, command->arguments) < 0 ){
perror(*command->arguments);
exit(EXIT_FAILURE);
}
} else if(pid < 0){
perror("error");
exit(EXIT_FAILURE);
}
command = command->next;
j++;
}
for(i = 0; i < 2 * numPipes; i++){
close(pipefds[i]);
printf("in parent: closed pipe[%d]\n", i);
}
wait(0);
}
}
どこかに漏れがあるか、記述子が見つからない可能性があります。どこに問題があるのか わからないようです。私は何を間違えましたか?ありがとう。
編集されたコード:
void runPipedCommands(cmdLine* command, char* userInput) {
int numPipes = countPipes(userInput);
int status = 0;
int i = 0, j = 0;
pid_t pid;
int pipefds[2*numPipes];
for(i = 0; i < (numPipes); i++){
if(pipe(pipefds + i*2) < 0) {
perror("pipe");
exit(EXIT_FAILURE);
}
}
j = 0;
while(command) {
pid = fork();
if(pid == 0) {
//if not first command
if(j != 0 && j!= 2*numPipes){
if(dup2(pipefds[j-2], 0) < 0){
perror(" dup2");///j-2 0 j+1 1
exit(EXIT_FAILURE);
}
}
//if not last command
if(command->next){
printf("command exists: dup(pipefd[%d], 1])\n", j+1);
if(dup2(pipefds[j + 1], 1) < 0){
perror("dup2");
exit(EXIT_FAILURE);
}
}
for(i = 0; i < 2*numPipes; i++){
close(pipefds[i]);
printf("in child: closed pipe[%d]\n", i);
}
if( execvp(*command->arguments, command->arguments) < 0 ){
perror(*command->arguments);
exit(EXIT_FAILURE);
}
} else if(pid < 0){
perror("error");
exit(EXIT_FAILURE);
}
command = command->next;
j+=2;
}
for(i = 0; i < 2 * numPipes; i++){
close(pipefds[i]);
printf("in parent: closed pipe[%d]\n", i);
}
wait(0);
}