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()?
Yes, you can. fprintf() syntax: int fprintf(FILE *stream, const char *format, parameters); Here stream can be specified to standard output by specifying stdout.
The pipe() function creates a data pipe and places two file descriptors, one each into the arguments fildes[0] and fildes[1], that refer to the open file descriptions for the read and write ends of the pipe, respectively. Their integer values will be the two lowest available at the time of the pipe() call.
The pipe function creates a pipe and puts the file descriptors for the reading and writing ends of the pipe (respectively) into filedes [0] and filedes [1] . An easy way to remember that the input end comes first is that file descriptor 0 is standard input, and file descriptor 1 is standard output.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With