【问题标题】:why cannot the parent read from child为什么父母不能从孩子那里读
【发布时间】:2015-04-09 14:51:31
【问题描述】:

这里我遇到了关于管道的问题。

如果我像这样在父管道中写入管道并从子管道中读取:

if(pid == 0){
    char str1[100];
    close(mypipe[1]);
    read(mypipe[0], str1, 6);
    close(mypipe[0]);
    exit(0);
}
else{
    while(wait(&state) != pid);
    char str[] = "hello!";
    close(mypipe[0]);
    write(mypipe[1], str, strlen(str)+1);
    close(mypipe[1]);
    printf("pipe: %s\n", str);
}

然后我可以得到打印“你好!”。

但是如果我像这样在孩子中写作并在父母中阅读:

if(pid == 0){
    char str[] = "hello!";
    close(mypipe[0]);
    write(mypipe[1], str, strlen(str)+1);
    close(mypipe[1]);
    exit(0);
}
else{
    while(wait(&state) != pid);
    char str1[100];
    close(mypipe[1]);
    read(mypipe[0], str1, 6);
    close(mypipe[0]);
    printf("pipe: %s\n", str);
}

然后它什么也不打印。

我真的不知道为什么......

【问题讨论】:

  • 在第一个示例中,读取端没有打印任何内容,因此您无法知道读取端是否真的收到了一些东西。您的 ptintf 在写入端。
  • 另外,第二个例子包含一个错误:str is not defined in this scope, but str1

标签: c unix pipe


【解决方案1】:

尽管您的第二个示例代码中存在错误(str 未在该范围内定义),尽管很明显Hello! 打印在您的第一个示例代码中,因为您刚刚定义了一个包含该内容的字符串并打印出来,你声称它不起作用的第二个代码实际上是有效的:

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

int main()
{
  int mypipe[2];
  int pid, state;

  pipe(mypipe);
  pid = fork();

  // Child writes, parent reads and prints
  if(pid == 0)
  {
    char str[] = "hello!";
    close(mypipe[0]);
    write(mypipe[1], str, strlen(str)+1);
    close(mypipe[1]);
    exit(0);
  }
  else
  {
    char str1[100];
    while(wait(&state) != pid);
    close(mypipe[1]);
    read(mypipe[0], str1, 100); // you should read at least 7 bytes, not 6,
                                // in order to receive the trailing \0 byte.
    close(mypipe[0]);
    printf("pipe: %s\n", str1);
  }
}

另一种方法是:

  // Parent writes, child reads and prints
  if(pid != 0)
  {
    char str[] = "hello!";
    close(mypipe[0]);
    write(mypipe[1], str, strlen(str)+1);
    while(wait(&state) != pid); // ensure child has read the pipe
    close(mypipe[1]);           // now we can close it
    exit(0);
  }   
  else
  {
    char str1[100];
    close(mypipe[1]);
    read(mypipe[0], str1, 100);
    close(mypipe[0]);
    printf("pipe: %s\n", str1);
  }

【讨论】:

  • 未定义的'str'是编辑时出错。现在代码在 Ubuntu 上可以正常运行,但在 UNIX V6 上仍然不打印任何内容。可能 UNIX V6 的系统函数 'pipe()' 有问题。非常感谢!
  • 一些 pipe() 实现的一端是只读的,一端是只写的。检查 write() 调用的返回值,如果失败,请使用 perror() 发出错误消息。这可能会告诉你出了什么问题。
猜你喜欢
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
相关资源
最近更新 更多