How can I redirect fprintf output to a socket?
I am editing source code which has a lot of fprintf calls. It logs to a file. But I would like to redirect this log to a socket.
How can this be done?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
On Unix-like systems, open the socket (getting a file descriptor).
Map socket to
stderrIf you’ve not yet used
stderr, you can simply usedup2()to make the socket into the output channel. You may be able to do that even if you have sent some data to the originalstderr. The suggestion in the comment about usingfflush()may be relevant, thoughstderris usually unbuffered rather than fully buffered (so there is not usually anything to flush).The
freopen()function can be used to change the output of a stream such asstderr(in particular). Hmmm, could you usefreopen()to mapstderrto/dev/fd/Nwhere N is the file descriptor of the socket? Yes, you probably could.Map socket to other stream
Re-reading your question – I don’t see
stderrin it. So thefdopen()function creates a stream from a file descriptor. So if you can specify the stream for the logging to write to, you’re home. If you can’t specify it but can see it, then thefreopen()trick above should work here too.