为什么 parent 不能从 child 读取

why cannot the parent read from child

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

如果我在 parent 中写入管道并从 child 中的管道读取,如下所示:

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

然后我可以打印 "hello!"。

但是如果我像这样在 child 中写入并在 parent 中读取:

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

然后什么都不打印。

真不知道为什么...

尽管您的第二个示例代码中存在错误(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 [=10=] 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);
  }