简体   繁体   English

如何使用 fprintf 并写入 pipe?

[英]How can I use fprintf and write to a pipe?

I created a pipe and I used dup2() to overwrite streams 1 & 2 (stdout & stderr) into those pipes.我创建了一个 pipe 并使用 dup2() 将流 1 和 2(stdout 和 stderr)覆盖到这些管道中。

Now I wish to use fprintf to write to stream 1 or 2, but my program doesn't seem to be receiving anything on the other side of the pipe.现在我希望使用 fprintf 写入 stream 1 或 2,但我的程序似乎在 pipe 的另一侧没有收到任何内容。 I've tried using printf(), but I'm not sure if this writes to stdout or stream 1 by default.我试过使用 printf(),但我不确定这是否默认写入标准输出或 stream 1。 If it writes to stream 1, I guess its a problem somewhere deeper in my code.如果它写入 stream 1,我猜它在我的代码更深的地方是一个问题。

Essentially I'm asking, given an int representing the stream, how can I get a FILE* suitable for use in fprintf()?本质上我在问,给定一个代表 stream 的 int,我怎样才能获得适合在 fprintf() 中使用的 FILE*?

If you have a file descriptor and want a FILE* , you can use fdopen如果你有一个文件描述符并且想要一个FILE* ,你可以使用fdopen

FILE *fdopen(int fd, const char *mode);

fdopen is a Posix function and documented in man fdopen . fdopen是 Posix function 并记录在man fdopen中。 To do the reverse you can usefileno要反过来,您可以使用fileno

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

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