为什么父母不能从孩子那里读书

时间:2015-04-09 14:51:32

标签: c unix pipe

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

如果我写在父母的管道中并从这样的孩子的管道读取:

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

然后它什么都不打印。

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

1 个答案:

答案 0 :(得分:0)

虽然您的第二个示例代码中存在错误(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);
  }