grepがブロックフェーズに入るのはなぜですか? [閉鎖]

grepがブロックフェーズに入るのはなぜですか? [閉鎖]

私は、ある子の出力を別の子の入力につなぐ任務を引き受けたテストを行っています。ps -ef最初のコマンドを使用しています(およびexeclp())2grep root番目のコマンドとして使用します(buを使用execlp())。目的の出力を取得していますが、grepの実行中にブロックされます。現在実行中であることを確認するためにtopコマンドを使用しました。プロセス。

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>

int main(){
    int status,i;
    int fds[2];
    pid_t pid;
    //pid=fork();;
    if(pipe(fds)==-1){
        perror("Error:");
        exit(0);
    }
    if(fork()>0){
        printf("The pid of the parent is %d\n",getpid());
        if(fork()==0){

            printf("The PID of the 2nd child %d\n",getpid());
            //printf("Inside 2nd child\n");
            close(0);
            dup(fds[0]);
            close(fds[1]);
            //fcntl(fds[0],F_SETFD,FD_CLOEXEC);
            //printf("The PID of the 2nd child %d\n",getpid());
            if(execlp("grep","grep","root",NULL)==-1){
                perror("ERROR FROM SECOND CHILD: ");
                exit(1);
            }

        }
        else{
            printf("The parent is waiting\n");
            /*for(i=0;i<2;i++){
                printf("%d The PID OF THE EXIT CHILD is %d\n",i,wait(&status));
            }*/
            while(wait(NULL)>0)
                perror("Error From Main:\n");
            //wait(&status);
            printf("The parent exited from the waiting stage\n");
            return 0;
        }

        //while(1);
    }
    else{
        close(1);
        dup(fds[1]);
        close(fds[0]);
        //close(1);
        printf("The pid of the First child is %d\n",getpid());
        if(execlp("ps","ps","-ef",NULL)==-1){
            perror("Error:");
            exit(1);
        }

    }

}

助けてください。私が殻を作っているからです。これを行う必要があります。

ベストアンサー1

パイプの他の書き込み側でEOFを取得できないため、grepプロセスがブロックされます。関連する書き込みファイル(fds [1])記述子が閉じられると、EOFはリーダー側に送信されます。私の間違いは、パイプに書き込むプロセスで書き込み記述子(fds [1])を閉じたにもかかわらず、親プロセス(main)で書き込み記述子(fds [1])を閉じなかったことです。

したがって、次のような質問が発生する可能性があります。記述子を使用しなくても記述子を閉じる必要がありますか?はいはい!親プロセスと子プロセスには同じディスクリプタのコピーがあるため、これらのディスクリプタはデフォルトでメモリ参照です(わかりません)。したがって、あるプロセスで閉じられても別のプロセスで別のコピーが開かれ、パイプからデータを読み取る3番目のプロセスがブロックされる可能性があります。

ファイル記述子を調べるために、cat /proc//を使用してデバッグしました。

おすすめ記事