- Learn Linux
- Learn Electronics
- Raspberry Pi
- LPI certification
- News & Reviews
6 August 2006
I use SSH to access my Linux machines over the network. This is usually fine, but if you close the session then any programs that you have run from the session are also closed. Occassionly it's nice to be able to set a program running and then leave it even when you've closed your session down.
If you are familiar with running commands in the background you may think that the solution is to run the command followed by an ampersand (&), which will run the program in the background. This does not normally work. Instead the correct solution is to run the nohup command. For example to run a program called myprog.sh then you would use
Obviously if you are wanting to run the command unattended it cannot provide visual feedback. So any text output that has not already been redirected (STDOUT and STDERR) is saved into a file called nohup.out.
Here is a short explanation about how this works:
When a process is run it has a parent process. When you run a command from a bash shell the bash shell is the parent process, and the command is the child. Whenever a parent process is killed (in this case cause by the terminal session ending), then it sends a SIGINT to it's child processes. The command should then terminate.
If the process is running the background (using the &) then this will still be a child process of the shell, and will still send the SIGINT and the command should terminate. The difference is that when the job is running in the background it frees up the shell for future use. Some commands will ignore the SIGINT instruction sent to it, and these are the ones that become orphen processes.
The nohup command is not tied to it's original parent process. It starts a new process which is owned by init (UID 1), so is not owned by the calling process.
You can see this with the ps command. I have used the yes command, which just prints y on the screen constantly (as it will not end when you don't want it to).
The following shows the yes command running on the command line:
user1 5009 4996 4 14:21 pts/1 00:00:00 yes
(field 2 is the process id = 5009, field 3 is the Parent Process id = 4996)
Running as a background task:
$ yes &
user1 5028 5017 3 14:21 pts/1 00:00:00 yes
But now running with the nohup command
$ nohup yes
user1 5060 1 99 14:22 ? 00:00:07 yes
Here you can see that the parent process id (PPID) is 1.
For more information on the nohup command see the nohup man page