我有一段标准代码,无法正确运行。读取总是返回零。write调用似乎卡住了,再也回不来了。我试过改变父母和孩子的顺序,但似乎不起作用。我想不出哪里不对。也许是虫子??请帮忙。

#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;

}

最佳答案

在创建管道之前,您需要先创建两个管道(四个文件描述符)。
因此,这两个过程中的一个过程中的fork与另一个过程中的fd[READ_END]没有任何关系。
它帮助我在每个进程中运行fd[WRITE_END],查看管道的工作情况。

关于c - 读写管道异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30623107/

10-11 22:49
查看更多