views:

77

answers:

2

Is there a way, in Bash, to capture/redirect the output (and stderr?) of a process once it's already running?

A: 

No there is not, at least, not really reliably.

When a process is forked, it has (at least) its first three file descriptors arranged by its parent before the fork(), so it inherits them.

After the fork, without kernel code, there is nothing that any process other than that process can do to them.

OK, well, almost nothing. The system calls that support debuggers (e.g. gdb) can be used to poke memory and force function calls in a process. In a test-tube, this can be used to close and reopen these streams. In real life, there's no telling if the process will be in a really unfortunate state when you catch it in the debugger, and will respond by self-immolation if you try this.

bmargulies
@bmargulies: cough *gdb*... cough *strace*. Cough *Redirect STDERR / STDOUT of a process AFTER it's been started, using command line?* http://stackoverflow.com/questions/593724 :)
Webinator
@Web cough kernel, but I see your point.
bmargulies
+1 for pointing out that this gdb hackery is in no way guaranteed to work correctly.
Jander
+4  A: 

It is possible using gdb. The question is already answered in this thread.

Juho Östman
Using the debugger to force code to run in the target process is hardly a 'bash' procedure.
bmargulies
@bmargulies: `(printf 'p dup2(open("/dev/null",1),1)\np dup2(1,2)\ndetach\n';sleep 1)|gdb -p $my_pid` passes well enough as a shellscript. Granted, `gdb` isn't POSIX, but then, neither are a lot of bash-isms :)
Jander