views:

402

answers:

1

I created a pipe and I used dup2() to overwrite streams 1 & 2 (stdout & stderr) into those pipes.

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. I've tried using printf(), but I'm not sure if this writes to stdout or stream 1 by default. If it writes to stream 1, I guess its a problem somewhere deeper in my code.

Essentially I'm asking, given an int representing the stream, how can I get a FILE* suitable for use in fprintf()?

+4  A: 

If you have a file descriptor and want a FILE*, you can use fdopen

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

fdopen is a Posix function and documented in man fdopen. To do the reverse you can use fileno

Johannes Schaub - litb
Do you close the descriptor, FILE pointer, either, or both?
Bernard
The file descriptor remains open until you fclose the stream, at which point it will close the file descriptor according to the manpage.
Johannes Schaub - litb