【问题标题】:Read Write misbehaving with pipes读写管道行为不端
【发布时间】:2015-06-03 14:33:15
【问题描述】:

我有一段标准的代码拒绝正确运行。读取始终返回零。 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;

}

【问题讨论】:

  • 你需要pipe()之前fork()

标签: c pipe fork ubuntu-12.04


【解决方案1】:

你是forking 创建管道之前,所以你确实在创建两个管道(四个文件描述符)。

因此,两个进程之一中的fd[READ_END] 无论如何与另一个进程中的fd[WRITE_END] 无关。

它帮助我在每个进程中运行 system("ls -l /proc/$$/fd/") 以查看管道是如何工作的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多