Redirecting/grep’ing an existing shell’s STDOUT

filesgnu-screenio-redirectionprocessstdout

I run a lot of long running processes (simulations) that print progress to STDOUT. I occasionally forget to redirect to STDOUT to a file I can grep, and it's usually too far along to restart.

QUESTION: Without stopping the process, is there a way I can hook into another STDOUT?

These are always running in GNU screen with ZSH on OS X 10.7.3.

Best Answer

There is a clever hack mentioned here that uses GDB to attach to the process, and a utility named dupx wraps up this functionality.

From the dupx manpage:

Dupx is a simple utility to remap files of an already running program. Shells like Bash allow easy input/output/error redirection at the time the program is started using >, < - like syntax, e.g.: echo 'redirect this text' > /tmp/stdout will redirect output of echo to /tmp/stdout.

Standard shells however do not provide the capability of remapping (redirecting) of output (or input, or error) for an already started process. Dupx tries to address this problem by using dup(2) system call from inside gdb(1). Dupx is currently implemented as a simple shell wrapper around a gdb script.

Related Question