从管道读取的子进程失败,并且似乎有故障

时间:2018-10-28 18:35:03

标签: c linux process pipe fork

我有以下输出代码:

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>

#define PIPE_STDIN  0
#define PIPE_STDOUT 1

#define msg "hello world"

int main()
{
   int fd_pipe[2];

   int ret = fork();
   if (ret < 0)
   {
       printf("Failed to fork\n");
       return -1;
   }
   else if (ret == 0)
   {
       printf("Parent with PID %d\n", getpid());    fflush(stdout);
       //sleep(3);
       ret = write(fd_pipe[PIPE_STDOUT], msg, sizeof(msg));   fflush(stdout);
       printf("Parent wrote string %d\n", ret);     fflush(stdout);
       wait( NULL );
       printf("Parent done wait\n");    fflush(stdout);
   }
   else
   {
       char buf[80];
       printf("Child with PID %d whose parent PID %d\n", getpid(), ret);    fflush(stdout);
       ret = read(fd_pipe[PIPE_STDIN], buf, sizeof(msg));
       printf("Child read %s %d\n", buf, ret);  fflush(stdout);
   }
}

输出:

Child with PID 1130 whose parent PID 1131
Child read   -1
Parent with PID 1131
hello world Parent wrote string 12
Parent done wait

从输出中,为什么子级无法从管道读取(返回-1),然后在打印“ hello world”消息时又失败了?请说明给出上述日志的执行顺序。

1 个答案:

答案 0 :(得分:2)

  1. 您应在pipe之前调用fork来初始化文件描述符。
  2. fork() == 0表示子进程。

关注code可能会起作用:

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>

#define PIPE_STDIN  0
#define PIPE_STDOUT 1

#define msg "hello world"

int main()
{
   int fd_pipe[2];
   int ret;

   if (pipe(fd_pipe) == -1) {
       perror("pipe");
       return -1;
   }
   ret = fork();
   if (ret < 0)
   {
       printf("Failed to fork\n");
       return -1;
   }
   else if (ret != 0)
   {
       printf("Parent with PID %d\n", getpid());    fflush(stdout);
       //sleep(3);
       ret = write(fd_pipe[PIPE_STDOUT], msg, sizeof(msg));   fflush(stdout);
       printf("Parent wrote string %d\n", ret);     fflush(stdout);
       wait( NULL );
       printf("Parent done wait\n");    fflush(stdout);
   }
   else
   {
       char buf[80];
       printf("Child with PID %d whose parent PID %d\n", getpid(), getppid());    fflush(stdout);
       ret = read(fd_pipe[PIPE_STDIN], buf, sizeof(msg));
       printf("Child read %s %d\n", buf, ret);  fflush(stdout);
   }
}