Redirect stdout/stderr of a background job from console to a log file?
I just run a job (assume foo.sh).
./foo.sh
[Press Ctrl-Z to stop]
bg # enter background
And it generate output to stdout and stderr. Is there any method to redirect to stdout and stderr to other file instead of current screen?
Apparently I misread your question the first time, so here's my updated answer:
After you sent your program to the background, you first have to find its PID
pgrep foo.sh
Then you could use gdb
to attach to that process
gdb -p <PID>
In gdb
you then change where this program writes to
p dup2(open("/path/to/file",577, 420), 1)
p dup2(1, 2)
then you detach from the process and quit gdb
detach
quit
A little explanation
-
577
is equivalent toO_CREAT|O_WRONLY|O_TRUNC
-
420
is equivalent toS_IRUSR|S_IWUSR|S_IRGRP|S_IROTH
- So the call to
open
opens the file and truncates it to 0 bytes if it exists or creates a new one with the right file permissions if it doesn't exist - The first call to
dup2
duplicates the file descriptor returned by the call toopen
to file descriptor1
(which isstdout
) - The second call to
dup2
duplicates the file descriptor1
to2
(which isstderr
)