c-从管道读取的子进程失败,并且似乎出现故障



我有以下输出代码:

#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 forkn");
return -1;
}
else if (ret == 0)
{
printf("Parent with PID %dn", getpid());    fflush(stdout);
//sleep(3);
ret = write(fd_pipe[PIPE_STDOUT], msg, sizeof(msg));   fflush(stdout);
printf("Parent wrote string %dn", ret);     fflush(stdout);
wait( NULL );
printf("Parent done waitn");    fflush(stdout);
}
else
{
char buf[80];
printf("Child with PID %d whose parent PID %dn", getpid(), ret);    fflush(stdout);
ret = read(fd_pipe[PIPE_STDIN], buf, sizeof(msg));
printf("Child read %s %dn", 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

从输出中,为什么child无法从管道中读取(返回-1(,然后在稍后打印消息"helloworld"?请解释给出上述日志的执行顺序。

  1. 您应该在fork之前调用pipe来初始化文件描述符
  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 forkn");
return -1;
}
else if (ret != 0)
{
printf("Parent with PID %dn", getpid());    fflush(stdout);
//sleep(3);
ret = write(fd_pipe[PIPE_STDOUT], msg, sizeof(msg));   fflush(stdout);
printf("Parent wrote string %dn", ret);     fflush(stdout);
wait( NULL );
printf("Parent done waitn");    fflush(stdout);
}
else
{
char buf[80];
printf("Child with PID %d whose parent PID %dn", getpid(), getppid());    fflush(stdout);
ret = read(fd_pipe[PIPE_STDIN], buf, sizeof(msg));
printf("Child read %s %dn", buf, ret);  fflush(stdout);
}
}

最新更新