简体   繁体   English

读写管道异常

[英]Read Write misbehaving with pipes

I have this standard piece of code which refuses to run correctly. 我有这段标准的代码,拒绝正确运行。 The read always returns zero. 读取总是返回零。 The write call seems to get stuck and never returns. 写调用似乎卡住了,再也不会返回。 I have tried changing the order of parent and child but does not seem to work. 我尝试更改父母和孩子的顺序,但似乎不起作用。 I fail to figure out whats wrong. 我不知道怎么了。 A bug perhaps?? 可能是个错误? Help would be appreciated. 帮助将不胜感激。

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define READ_END 0
#define WRITE_END 1

int main()
{
  int pid;//,bytes;
  pid=fork();
  char buffer[100];
  char msg[]="Hello";
  //const char *msg2="Hi";
  int fd[2];
  //int p2[2];

  /* create the pipe */
  if (pipe(fd) == -1) 
  {
    fprintf(stderr,"Pipe failed");
    return 1;
  }


  if (pid < 0) 
  { /* error occurred */
    fprintf(stderr, "Fork Failed");
    return 1;
  }
  if (pid > 0) 
  { /* parent process */
    /* close the unused end of the pipe */
    close(fd[WRITE_END]);
    /* read from the pipe */
    int bytesRead = read(fd[READ_END], buffer, 100);
    printf("read %d",bytesRead);
    /* close the write end of the pipe */
    close(fd[READ_END]);
    wait(NULL);
  }
  else 
  { 
    /* child process */
    /* close the unused end of the pipe */
    close(fd[READ_END]);
    /* write to the pipe */
    int bytesWritten = write(fd[WRITE_END], msg, strlen(msg)+1);
    printf("%d",bytesWritten);
    /* close the write end of the pipe */
    close(fd[WRITE_END]);


  }

  return 0;

}

You're fork ing before creating the pipe, so you are indeed creating two pipes (four file descriptors). 创建管道之前就进行了fork ,因此实际上您正在创建两个管道(四个文件描述符)。

So, the fd[READ_END] in one of the two process isn't related anyhow with the fd[WRITE_END] in the other process. 因此, fd[READ_END]在这两个过程中的一个不无论如何与相关fd[WRITE_END]在其他进程中。

It has helped me to run system("ls -l /proc/$$/fd/") in each process to see how the pipes are working. 它帮助我在每个进程中运行system("ls -l /proc/$$/fd/")来查看管道的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM