【问题标题】:Reading from pipe goes wrong从管道读取出错
【发布时间】:2021-12-11 19:10:11
【问题描述】:

我想从管道中读取整数然后打印它,但每次它都会打印垃圾值。谁能帮帮我?

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

【问题讨论】:

  • 你做事的顺序不对:你应该在创建管道之后创建一个新进程。否则,每个进程将创建自己的一组管道,每个管道都不为其他进程所知。
  • 另外,总是检查错误。您必须检查 readwrite 返回的内容。还要记住(尽管不太可能)即使fork 也可能失败。
  • 谢谢你们,我犯了一个非常愚蠢的错误
  • @hasan 我犯的非常愚蠢的错误 欢迎编写代码,您看不到自己的错误,但其他人可以。

标签: c process pipe garbage


【解决方案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]);
    }
}

【讨论】:

  • 可以通过提供一些代码来改进答案,这些代码显示您为解决问题所做的更改。
  • 确定我发布了代码
猜你喜欢
  • 1970-01-01
  • 2020-07-18
  • 2023-03-06
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多