Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between nohup and ampersand

Tags:

linux

bash

nohup

Both nohup myprocess.out & or myprocess.out & set myprocess.out to run in the background. After I shutdown the terminal, the process is still running. What's the difference between them?

like image 937
Yarkee Avatar asked Oct 21 '22 18:10

Yarkee


People also ask

What is the use of & in nohup?

The & symbol tells the shell to run the command in the background. It is similar to the above nohup command except that when the session ends, it returns immediately to the shell prompt. To bring it back to the forefront, use the “fg” command. The output of all the commands you execute will be appended to the nohup.

What is & at the end of nohup?

using nohup + ampersand (&) will do the same thing, except that when the session ends, the parent of the child process will be changed to "1" which is the "init" process, thus preserving the child from being killed.

What does nohup stand for?

nohup is a POSIX command which means "no hang up". Its purpose is to execute a command such that it ignores the HUP (hangup) signal and therefore does not stop when the user logs out.

Is nohup necessary?

You don't necessarily need to use nohup. out , though – it's just the default. You can specify a custom output when you run nohup and place it in a custom location. The custom output contains exactly the same data as the standard nohup.


1 Answers

nohup catches the hangup signal (see man 7 signal) while the ampersand doesn't (except the shell is confgured that way or doesn't send SIGHUP at all).

Normally, when running a command using & and exiting the shell afterwards, the shell will terminate the sub-command with the hangup signal (kill -SIGHUP <pid>). This can be prevented using nohup, as it catches the signal and ignores it so that it never reaches the actual application.

In case you're using bash, you can use the command shopt | grep hupon to find out whether your shell sends SIGHUP to its child processes or not. If it is off, processes won't be terminated, as it seems to be the case for you. More information on how bash terminates applications can be found here.

There are cases where nohup does not work, for example when the process you start reconnects the SIGHUP signal, as it is the case here.

like image 384
nemo Avatar answered Oct 24 '22 08:10

nemo