What is the function of the nohup command?
Solution 1:
Let us consider you have opened a gedit
text editor from a terminal and working on it. If you close the terminal before closing gedit
, the gedit also gets closed as soon as closing the terminal. So what is going on here? The gedit
runs as a child process under the terminal. When you close the terminal a hang up signal (SIGHUP
) is sent to the process which kills the child process.
On the other hand if you want your child process (here gedit
) to keep on running even after closing the parent terminal, you would want your process immune to hangup signal. So that closing the terminal do not close the child process. nohup
does exactly this job.
nohup
does not disconnect a command from terminal, it makes your script ignore SIGHUP, and redirects stdout/stderr to a file nohup.out, so that the command can continue running in the background after you log out. If you close the shell/terminal or log off, your command is no longer a child of that shell. It belongs to init process. If you search in pstree
you'll see it is now owned by process 1 (init). That cannot be brought back to the foreground because the foreground no longer exists.
Solution 2:
Besides what @sourvac wrote, this is a legacy from Back In The Day when people logged in via text-only dumb terminals, often via (the original, analog 110 baud) modem: the "hang up" is literally "hanging up the phone".
A pid that's immune to hangup signal will keep on running even after you log out and hang up the phone. This was very useful on slow computers when jobs ran for hours upon hours, and you couldn't just stay logged in (someone else needed to use the terminal, you needed to use the phone, static in the line might "bzzt" the connection, etc).