简体   繁体   English

将printf重定向到管道C

[英]redirectioning printf to pipe C

The code above does not give any warnings or errors, but the parent does not print the string passed with the pipe. 上面的代码没有给出任何警告或错误,但是父级不会打印随管道传递的字符串。 Any idea? 任何想法?

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 pipe\n");
    fflush(stdout);
}
else { /*Parent*/
    close (fd[1]);
    num_bytes_read = read (fd[0], buffer, sizeof (buffer));
    printf ("The received string is: %s\n", buffer);
}
return (0);

In the child process, you use printf(3) which tries to write to stdout . 在子进程中,您使用printf(3)尝试写入stdout

If you want to write to pipe, you can use write(2) , just like you used read(2) to read from it for the parent process. 如果要写入管道,则可以使用write(2) ,就像使用read(2)从其为父进程读取一样。

In the child you are writing to FILE* which you have just closed (ie stdout). 在孩子中,您正在写入刚刚关闭的FILE *(即stdout)。 With dup you have assigned to fd == 0 the descriptor of the pipe, but the structure where stdout points remains "closed". 使用dup,您已将fd == 0分配给管道的描述符,但是stdout点所在的结构保持“封闭”。 Either write to pipe using write (as suggested by @chrk) or do close(STDOUT_FILENO) instead of fclose(stdout) , or maybe you can also reassign to stdout a new value obtained from fdopen . 使用write写入管道(如@chrk所建议),或者执行close(STDOUT_FILENO)代替fclose(stdout) ,或者也可以重新分配以从fdopen获得的新值stdout。

Use dup2. 使用dup2。 You are assuming that dup is returning 1, but you have no way of knowing that. 您假设dup返回1,但是您无法得知。 Also, since you've already closed stdout, the call to printf is probably failing. 另外,由于您已经关闭了stdout,因此对printf的调用可能会失败。 Check the return value. 检查返回值。 Instead of fclosing stdout, you can close the underlying file descriptor, but that's not good practice. 除了关闭标准输出,您还可以关闭基础文件描述符,但这不是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM