0

複数のパイプを使用して次の Linux コマンドを実行する C プログラムを作成しています。

猫 myfile1.txt | egrep コンピューティング | wc -l > myfile

私のコードは次のとおりです。

    int p_fd[2];
    pid_t childpid, waitReturn;
    int pid=1;
    int status, i;

    pipe(p_fd);

    for( i = 1 ; i < 3 ; i++ )
        if( childpid = fork() )
            break;
        else
            pid++;

    while( childpid != ( waitReturn = wait( &status ) ) )
        if( ( waitReturn == -1 ) && ( errno != EINTR ) )
            break;

    if ( childpid > 0 && pid == 1 ){
        printf("%d\n", pid);
        int fd;
        if ( ( fd= open("myfile", O_CREAT|O_RDWR|O_TRUNC, 00644)) == -1 )
        {
                printf("Error: Cannot open file in open()\n");
                exit(1);
        }
        close(0);
        dup(p_fd[0]);
        close(1);
        dup(fd);
        close(p_fd[0]);
        close(p_fd[1]);
        close(fd);
        execl("/bin/wc", "wc", "-l", NULL);
    }else if( childpid > 0 && pid == 2 ){
        printf("%d\n", pid);
        close(0);
        dup(p_fd[0]);
        close(1);
        dup(p_fd[1]);
        close(p_fd[0]);
        close(p_fd[1]);

        execl("/bin/egrep", "egrep", "Computing", NULL);

    }else if( childpid == 0 && pid == 3 ){
        printf("%d\n", pid);
        close(1);
        dup(p_fd[1]);
        close(p_fd[0]);
        close(p_fd[1]);

        execl("/bin/cat", "cat", "myfile1.txt", NULL);
    }   

    return 0;

ただし、pid 2 の 2 番目の子で呼び出される "execl("/bin/egrep", "egrep", "Computing", NULL);" に達すると、プログラムがハングします。

プログラムがハングする理由がわかりません。パイプのデッドロックについてですか?

希望の結果が得られるように、上記のプログラムを変更するのを手伝ってくれる人はいますか?

4

1 に答える 1