- pipe2 つの子プロセスの間に を作成しました。まず、- ls適切な fd に書き込む を実行- grep rし、適切な fd から読み取るを実行します。
- コマンドが正常に機能することを端末で確認できます - grep(出力)
- 問題は、もう実行されていなくて - grepも、終了せず、そこにとどまることです- ls
他のプログラムでは正常にpipe動作します..
for (i = 0; i < commands_num ; i++) {   //exec all the commands instants
    if (pcommands[i]._flag_pipe_out == 1) { //creates pipe if necessary 
        if (pipe(pipe_fd) == -1) {
            perror("Error: \"pipe()\" failed");
        }
        pcommands[i]._fd_out = pipe_fd[1];
        pcommands[i+1]._fd_in = pipe_fd[0]; 
    }
    pid = fork();   //the child exec the commands  
    if (pid == -1) {
        perror("Error: \"fork()\" failed");
        break;          
    } else if (!pid) { //child process
        if (pcommands[i]._flag_pipe_in == 1) {  //if there was a pipe to this command
            if (dup2(pcommands[i]._fd_in, STDIN) == -1) {
                perror("Error: \"dup2()\" failed");
                exit(0);
            }
            close(pcommands[i]._fd_in);
        }
        if (pcommands[i]._flag_pipe_out == 1) { //if there was a pipe from this command
            if (dup2(pcommands[i]._fd_out, STDOUT) == -1) {
                perror("Error: \"dup2()\" failed");
                exit(0);
            }
            close(pcommands[i]._fd_out);
        } 
        execvp(pcommands[i]._commands[0] , pcommands[i]._commands); //run the command
        perror("Error: \"execvp()\" failed");
        exit(0);
    } else if (pid > 0) { //father process
    waitpid(pid, NULL, WUNTRACED);
    }
}
//closing all the open fd's
for (i = 0; i < commands_num ; i++) {
    if (pcommands[i]._fd_in != STDIN) { //if there was an other stdin that is not 0
        close(pcommands[i]._fd_in);
    }           
    if (pcommands[i]._fd_out != STDOUT) { //if there was an other stdout that is not 1
        close(pcommands[i]._fd_out);            
    }   
}
だから、私は "コマンド" インスタントpcommands[i]
を持っています。これには、pipein、pipeout fdin、fdout のフラグ、および char** ("ls -l" のような実際のコマンドの場合) があります。
すべてが良いとしましょう。つまり、次のことを意味します。
pcommands[0]:
pipein=0
pipeout=1
char** = {"ls","-l",NULL}
pcommands[1]:
pipein=1
pipeout=0
char** = {"grep","r",NULL}
これで、ループが 2 回実行されます (コマンド インスタントが 2 つあるため) 最初に、pcommands[0] has pipeout==1 create pipe do fork pcommands[0] has pipeout==1 child: dup2 to が表示されます。 stdout execvp
2 回目: パイプを作成しません。子をフォークします: pcomands[1] には pipein==1 があります。
このコマンドは機能します。私の出力は次のとおりです。
errors.log exer2.pdf multipal_try
(「r」を含むすべてのもの)しかし、その後、スタックし、抜け出せませんgrep..私が見ることができる他の端末でgrepは、まだ動作しています
閉じる必要があるすべての fd を閉じることを願っています...
うまくいかない理由がわかりません。正しく動作しているように見えます (まあ、他のコマンドでも動作します..)
誰か助けてくれませんか?ありがとう