-4

Linux で C 言語でパイプラインを学習しようとしています。以下のプログラムを書きます。このプログラムにエラーはありませんか?

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


int main (void)
{
    int fd[2], nbytes;
    pid_t childpid;
    char string[]= "Hello, World!\n";
    char readbuffer[80];


    pipe(fd);

    if((childpid = fork()) == -1)
    {
        perror("fork");
        exit(0);    
    } 

    if(childpid == 0)
    {
        // child process closes up input side of pipe.
        close(fd[0]);

        // send "string" through the output side of pipe.
        write(fd[1], string, strlen(string));
        exit(0);
    }

    else
    {
        // parent process closes up output side of pipe.
        close(fd[0]);

        // Read in a string from pipe.
        nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
        printf("Received string = %s\n", readbuffer);
    }

    return 0;
}

何か問題ある?

4

1 に答える 1

1

以下の 2 つのコード セグメントのうちの 1 つは、単にコメントに基づいて間違っています。

if (childpid == 0)
{
    // child process closes up input side of pipe.
    close(fd[0]);

と:

else
{
    // parent process closes up output side of pipe.
    close(fd[0]);

実際にfd[1]は、親 (書き込み側) で閉じる必要があります。驚いたことに、あなたのread呼び出しは正しいですが、オリジナルで閉じたばかりのファイル記述子から読み取っています。

読んだもののみを印刷する必要があることに注意してください(そして、何かを正常に読み取った場合のみ):

if (nbytes > 0)
    printf("Received string: <<%.*s>>\n", nbytes, readbuffer);
else if (nbytes == 0)
    printf("Received no data\n");
else
    printf("Received error (%d: %s)\n", errno, strerror(errno));

(最後の行を正しくコンパイルするには、<errno.h>との両方が必要になることに注意してください。)<string.h>

<<およびマーカーは、>>末尾の空白などを確認できるようにするためのものです。必要に応じて省略できます。

于 2012-10-28T17:41:59.390 に答える