1

私はパイプとフォークを学んでいます。この例では、親から子に同じ単語を書き込もうとしています。これが私が書いたいくつかの練習コードです(4人の子供):

#define MAXWORD 5

int main() {

    pid_t parentID, pid, fd[2];
    int i, j, k;
    int status = 0;
    char toWrite[5] = "abcd";

    pipe(fd);
    parentID = getpid();

    for (i = 0; i < 4; i++) {

        if (getpid() == parentID) {
            pid = fork();
        }

        if (pid < 0) {
            perror("fork");
            exit(1);

        } else if (pid == 0) {
            close(fd[1]);

            printf("Reading ...\n");            
            char buf[MAXWORD];
            read(fd[0], buf, MAXWORD);

            printf("CHILD : %d\tread : %s\n", getpid(), buf);

            exit(0); // edited

        }

    }

    for (k = 0; k < 4; k++) {
        if (getpid() == parentID) {
            close(fd[0]);
            printf("Writing ...\n");
            write(fd[1], toWrite, MAXWORD);

            wait(&status); // edited
        }
    }

    return 0;
}

コードからの出力は次のとおりです。

Reading ...
Writing ...
CHILD : 1457    read : abcd
Writing ...
Reading ...
Reading ...
Writing ...
Writing ...
CHILD : 1458    read : abcd
CHILD : 1457    read : abcd
Reading ...
Reading ...
CHILD : 1458    read : abcd
Reading ...
Reading ...
Reading ...
CHILD : 1458    read : abcd
CHILD : 1459    read : 
Reading ...
CHILD : 1459    read : 
CHILD : 1460    read : 
CHILD : 1457    read : abcd
Reading ...
CHILD : 1457    read : abcd

フォークが行われるループのelse if句に書き込みステートメントを入れると、正常に機能します。ただし、子が作成された後に書き込もうとすると、うまく機能しません。

編集:「編集済み」とマークされた行を追加した後、プログラムは期待どおりに動作します。これは正しい方法でしょうか?

そして、入力は大歓迎です。ありがとうございました。

4

1 に答える 1

1

When the parent exits, the pipe closes. The children will then have their reads satisfied with 0 bytes. (You should check the return code from the read.) Each child is also reading N times due to the loop. The first child 4 times, the second child 3 times, etc. Since all of the children are reading the same pipe, any one of them could satisfy the read.

于 2013-03-19T01:49:33.067 に答える