Send Foreground job to background redirecting output

I have many CPU intensive processes running and sometimes I run them in the foreground so that I can see what the output is.

I want to send that foreground process to the background, but also have it direct the output to a logfile.

I know to send something to the bg I do

Ctrl-z on the FG job and then

 bg %1 

is there a way to send the output of that process to the background...

for instance (and this does not work)

 bg %1 > somelogfile.log &

thanks

The shell does redirection before it creates a process, not after, so you're out of luck there. You can't redirect a running process unless you're using something like screen which uses socket or tty tricks to do so.

Just a small thought...

Assume a process(test.sh) is running with a pid xxx

If we give the SIGSTP signal, say

kill -17 xxx

, it will signal the process

[1] + Stopped (SIGSTOP)        sh test.sh

now, why cant we give bg which will change it to running in bg?

@corona688 ok so it creates the output at the initial process call. what if i were to start it in the background with a logfile...is there a way to bring it into the FG?

@dennis.jacob - yea it can be sent into the background by just doing bg, but then I can't log the output in a logfile

I repeat: The shell cannot redirect output for a process that already exists. You can't just reach in and change a completely different process' file table for it.

The shell has to do all redirection for a new process before the new process is run -- it does this by creating a subshell, which does all redirection, then replaces itself with the new program but keeping I/O redirections intact. Once that's done, the new process controls its own output like any other program.

If you want to view the logfile as its written to, try 'tail -f logfile'. This will watch logfile for new lines and print them to standard output.

There's also the screen terminal/utility/shell/thing, which uses network sockets to do something similar to you want. It keeps sessions that you can connect and disconnect to without killing or halting them.

ok. just thought id see if the opposite was possible. the tail -f logfile approach seems to be the best option here. thanks big guy

This will send the standard output of bg to somelogfile.log, not %1.