从管道读取错误

Reading from pipe goes wrong

我想从管道中读取整数然后打印它,但每次它都打印垃圾值。有人可以帮助我吗?

int main()
{
    int pid1 = fork();

    int fd1[2];
    pipe(fd1);

    if (pid1 == 0) // Child process
    {
        int x;
        close(fd1[1]);
        read(fd1[0], &x, sizeof(int));
        printf("I'm the First Child and I received: %d\n", x);   // <--- Here it prints garbage value
        close(fd1[0]);
    }

    else // Parent process
    {
        int x = 5;
        close(fd1[0]);
        write(fd1[1], &x, sizeof(int));
        close(fd1[1]);
    }
}

我必须在创建管道后 fork()。所以代码看起来像这样:

int main()
{
    int fd1[2];
    pipe(fd1);

    int pid1 = fork();

    if (pid1 == 0) // Child process
    {
        int x;
        close(fd1[1]);
        read(fd1[0], &x, sizeof(int));
        printf("I'm the First Child and I received: %d\n", x); 
        close(fd1[0]);
    }

    else // Parent process
    {
        int x = 5;
        close(fd1[0]);
        write(fd1[1], &x, sizeof(int));
        close(fd1[1]);
    }
}