Suppose my program prints to multiple file descriptors and I need to watch all of the outputs as they are being printed but only save stdout
to a file. How do I do that?
1 Answers
Suppose 3 is one of those file descriptors you're interested in.
3 may be pointing to file
, for example:
exec 3>file
Your app writes to 3:
app() { echo hello world >&3; }
If you want to interecept 3, you need to dup
it to another file descriptor (e.g., 4):
exec 4>&3
and redirect (=replace) 3 with a pipe to your interceptor process, which has to write back to the original target (or else it wouldn't be an interceptor), which is now saved in fd 4:
app 3> >(tee /dev/tty >&4) #this interceptor writes to the terminal
The above should print hello world
to the terminal and file
should end up with hello world
as well.
All this assume these filedescriptors are open before you start the process. If you want to intercept filedescriptor outputs dynamically at runtime, then I'm afraid you have to modify the code, inject code at runtime, or intercept system calls with something like ptrace
.

- 28,816