将 printf 重定向到管道 C



上面的代码没有给出任何警告或错误,但父级不会打印随管道传递的字符串。知道吗?

pid_t pid;
int fd[2];
int num_bytes_read;
char buffer[80];
pipe (fd);
pid=fork();
if (pid == 0) {/*Son*/
    fclose(stdout);
    close(fd[0]);
    dup(fd[1]);
    printf ("write in pipen");
    fflush(stdout);
}
else { /*Parent*/
    close (fd[1]);
    num_bytes_read = read (fd[0], buffer, sizeof (buffer));
    printf ("The received string is: %sn", buffer);
}
return (0);

在孩子中,您正在写入刚刚关闭的 FILE*(即标准输出)。使用 dup,您已将管道的描述符分配给 fd == 0,但stdout点的结构保持"封闭"。要么使用write(如@chrk所建议的那样)写入管道,要么执行close(STDOUT_FILENO)而不是fclose(stdout),或者您也可以将从fdopen获得的新值重新分配给stdout。

在子进程中,您使用尝试写入stdoutprintf(3)

如果要写入管道,可以使用 write(2) ,就像使用read(2)读取父进程一样。

使用 dup2。 您假设 dup 返回 1,但您无法知道这一点。 此外,由于您已经关闭了标准输出,因此对 printf 的调用可能会失败。 检查返回值。您可以关闭基础文件描述符,而不是关闭标准输出,但这不是好的做法。

最新更新