Detach process/program from current shell to keep it alive after logout

Every program you run from your working shell is to Linux system regarded as process. Each process except init have its our parent identified by PPID. When you start process using your current shell the shell itself becomes a parent for your newly started process. The trouble with this approach is that this may not be always desirable since when parent process is terminated its child dies with it. The happens very often when login into server using ssh, telnet etc. After log out parent shell is terminated and thus terminating all processes forked from it. Let’s explore some way how to avoid this necessary but sometime undesired system behavior:

nohup command

The most easiest way to continue running your process after ssh logout is to use nohup command. To start process and be able to continue run your process after logout prefix your command with nohup and suffix with & sign. Example:

$ nohup &
nohup: ignoring input and appending output to ‘nohup.out’

Entire output if any is appended to nohup.out file for later review

at command

perhabs even simple way to detach your process from current working shell is by using at command. The below example illustrates how to run job in this case yes command imitatively and at the same time detaching this process form a current working shell.

$ at now
at> yes > /dev/null
job 2 at Thu Jun 26 11:12:00 2014

On the first line we started at command with time argument “now”. Next, we time command we wish to run. lastly, by pressing CTRL+D key combination we send EOT ( End Of Text ) signal that we are done issuing commands and the job will start immediately. Listing current jobs using jobs command will produce no output which means we are free to disengage from our current shell without stopping any processes.

disown command

If trom some reasons have have forgotten to start your process with either of the above methods you still are able to detach your process from current shell using disown command. For example here is yes command running in background:

 $ jobs
[1]+  Running                 yes > /dev/null &

if we log out now the process will be terminated and therefore we need to detach it form our current shell first:

$ disown %1
$ jobs
$ ps aux | grep yes
lubos   9257 96.9  0.0 107892   352 pts/5    R    11:23   1:30 yes

As you can see our process is no longer attached to our current shell.