首页 > 解决方案 > 从管道读取出错

问题描述

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

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]);
    }
}

标签: cprocesspipegarbage

解决方案


我必须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]);
    }
}

推荐阅读