0

I know already how to implement methods regarding usual freopen(), popen() or similar stdout/stdin/stderr -based redirecting mechanisms, but I wondered how should I apply the said mechanism to static (own) libraries in C? Say, I want to use a library to capture any program with printf() commands or so into a file (for instance) without letting it appear on the console - are there some things I need to acknowledge before applying simple fd dups and just calling the library in the main program? Even piping seems to be complex seeing as execing here is risky...

thanks in advance.

4
  • So you want to redirect stdout for any program using your static library? Commented Nov 30, 2015 at 22:36
  • yes, I want to redirect stdout to a file in any program by using my static library. Commented Nov 30, 2015 at 22:44
  • What operating system are you programming for? You can try to do this in plain C, but the solution may not interact correctly with direct read() / write() based IO. Commented Nov 30, 2015 at 22:48
  • Ubuntu 14.04 (of course one might try to suggest ready-made functions for console a la "someprogram > log.txt" as a case in point but I am willing to go for a bit more interesting alternative (i.e. c program). Commented Nov 30, 2015 at 22:54

1 Answer 1

2

There's an old-timers' trick to force the entire process, regardless of what library the code comes from, to have one of the standard IO ports connected to a different filehandle. You simply close the filehandle in question, then open a new one. If you close(1), then open('some_file', 'w'), then ALL calls that would result in a write to stdout will go to some_file from that point forward.

This works because open() always uses the first file descriptor that isn't currently in use. Presuming that you haven't closed stdin (fd=0), the call to open will get a file descriptor of 1.

There are some caveats. FILE outputs that haven't flushed their buffers will have undefined behavior, but you probably won't be doing this in the middle of execution. Set it up as your process starts and you'll be golden.

Sign up to request clarification or add additional context in comments.

4 Comments

I imagine you're going to... upset ...some individuals with the use of "old-timers" ;)
You could also dup (2) the descriptor to the one you want, instead of relying on open.
Library duping resulted in my output appearing on console as well (after library return) - which is not what I really want :/
You MUST close stdout first, no matter which method you choose. dup also chooses the first unused file descriptor and you need to vacate fd=0 before you do either dup or open.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.