Wednesday, November 5, 2008

Ubuntu Linux Command Line Background Magic (without screen)

This is useful when you are in an ssh session and you want to background a long-running task and log out. The job will continue running after you log out, and you can even log back in later and resume it. This solution does not require screen.

~$ nice -n10 -- super_long_running_script
...

Now say that the script is taking for ever, and you need to kill your ssh session. First, hit + Z

...
[1]+ Stopped(SIGTSTP) nice -n10 -- super_long_running_script
~$

This will stop the task (but not kill it) and give you a console again. Note that the [1] indicates that the task is indexed as job 1. Next, we want to resume the task again, but in the background:

~$ bg 1
[1] nice -n10 -- mysql -u root bamboo_staging <backup_20081105.sql &
~$

the number "1" corrolates with the job number above. The task is now running again in the background. Note that if you log out now bash will kill the task because bash kills its children on exit. To prevent bash from killing the child, do:

~$ disown -h 31968

Where 31968 is the PID of the backgrounded process. Now you can exit your ssh shell:

~$ exit
...

Note that your ssh session doesn't really close properly. However it is now safe to kill your ssh client. The backgrounded process will happily keep running.

No comments: