2

fork()コマンドの使用方法と、親とその子の間でデータをパイプする方法を学びます。私は現在、フォークとパイプの機能がどのように機能するかをテストするための簡単なプログラムを作成しようとしています。私の問題は、待機機能の正しい使用/配置にあるようです。親に、両方の子の処理が完了するのを待ってもらいたい。これが私がこれまでに持っているコードです:

int main(void)
{
    int n, fd1[2], fd2[2];
    pid_t pid;
    char line[100];

    if (pipe(fd1) < 0 || pipe(fd2) < 0)
    {
        printf("Pipe error\n");
        return 1;
    }

    // create the first child
    pid = fork();

    if (pid < 0)
        printf("Fork Error\n");
    else if (pid == 0)  // child segment
    {
        close(fd1[1]);  // close write end
        read(fd1[0], line, 17); // read from pipe
        printf("Child reads the message: %s", line);

        return 0;
    }
    else    // parent segment
    {
        close(fd1[0]);  // close read end
        write(fd1[1], "\nHello 1st World\n", 17);   // write to pipe

        // fork a second child
        pid = fork();

        if (pid < 0 )
            printf("Fork Error\n");
        else if (pid == 0) // child gets return value 0 and executes this block
            // this code is processed by the child process only
        {
            close(fd2[1]);  // close write end
            read(fd2[0], line, 17); // read from pipe
            printf("\nChild reads the message: %s", line);
        }
        else
        {
            close(fd2[0]);  // close read end
            write(fd2[1], "\nHello 2nd World\n", 17);   // write to pipe

            if (wait(0) != pid)
                printf("Wait error\n");
        }

        if (wait(0) != pid)
            printf("Wait error\n");

    }

    // code executed by both parent and child
    return 0;
}   // end main

現在、私の出力は次のように見えます。

./fork2 
Child reads the message:  Hello 1st World 
Wait error

Child reads the message:  Hello 2nd World 
Wait error

親を待たせるのに適切な場所はどこですか?

ありがとう、

トメック

4

2 に答える 2

4

それはほとんど問題ないようです(私はそれを実行しませんでした、気をつけてください)。あなたの論理エラーは、子が特定の順序で終了すると仮定することです。wait(0)どの pid を取得するかが確実にわかっていない限り、特定の pid に対するの結果をチェックしないでください。

編集:

私はあなたのプログラムを実行しました。少なくとも 1 つのバグ (2 番目の子プロセスの呼び出しwait()) がありますが、おそらくやりたくないでしょう。コードの一部を関数に分割することをお勧めします。これにより、実行中の操作の順序が混乱することなく明確にわかります。

于 2010-02-16T05:54:07.503 に答える
0

すべての子供たちを待つために、このようなものを使用する方が良いと思います。

int stat;
while (wait(&stat) > 0)
   {}   
于 2010-02-19T18:16:34.460 に答える