1

標準ライブラリ関数または標準I/Oストリームを使用する代わりに、フォークとパイプを使用して文字列「helloworld」を別のchar配列にコピーする次のコードを記述しました。プログラムは正常にコンパイルされていますが、出力がありません。それでも、printfの出力は表示されていません。

# include <string.h>
# include <unistd.h>
# include <stdio.h>

char string[] = "hello world";

int main()

{

        int count, i;
        int toPar[2], toChild[2];
        char buf[256];
        pipe(toPar);
        pipe(toChild);

        if (fork() == 0)
        {
                printf("\n--- child process ---");
                close(0);
                dup(toChild[0]);
                close(1);
                dup(toPar[1]);
                close(toPar[1]);
                close(toChild[0]);
                close(toPar[0]);
                close(toChild[1]);
                for (;;)
                {
                        if ((count = read(0, buf, sizeof(buf))) == 0)
                                break;
                        printf("\nChild buf: %s", buf);
                        write(1, buf, count);
                }
        }

        printf("\n--- parent process ---");
        close(1);
        dup(toChild[1]);
        close(0);
        dup(toPar[0]);
        close(toPar[1]);
        close(toChild[0]);
        close(toPar[0]);
        close(toChild[1]);
        for (i = 0; i < 15; i++)
        {
                write(1, string, strlen(string));
                printf("\nParent buf: %s", buf);
                read(0, buf, sizeof(buf));
        }
        return 0;

   }
4

3 に答える 3

4

あなたprintfはに書き込みをstdout行っていますが、親と子の両方で、ファイル記述子1をパイプにリダイレクトしているので、そこにprintf出力が送信されます。

の代わりに-をprintf(...)使用すると、がまだ端末を指しているfprintf(stderr, ...)ため、出力を確認できます。stderr

いくつかのバグがあることに注意してください。

  • 子はそれが完了したときに呼び出す必要があります_exit(0)。そうしないと、親コードにドロップされます。
  • nulターミネータを書き込むように、writeを使用する必要があります。strlen(string) + 1
于 2010-01-19T10:39:48.360 に答える
0

次のような「\n」を追加してみてくださいprintf("\nParent buf: %s\n", buf);

于 2010-01-19T10:19:14.180 に答える
0

これらのパイプはブロッキング IO を実行していると思います。そのため、パイプが他のプロセスによって閉じられない限り、 read は返されません。それと、バッファリングされた IO を行う printf により、出力が得られなくなります。

于 2010-01-19T10:30:47.293 に答える