Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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()?

like image 235
samoz Avatar asked Mar 16 '09 13:03

samoz


People also ask

Can fprintf write to stdout?

Yes, you can. fprintf() syntax: int fprintf(FILE *stream, const char *format, parameters); Here stream can be specified to standard output by specifying stdout.

Does pipe create the file descriptors?

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.

What does pipe do to the file descriptor?

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.


1 Answers

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

like image 192
Johannes Schaub - litb Avatar answered Sep 17 '22 03:09

Johannes Schaub - litb