I am having trouble understanding the difference between using just nohup to run a script and using nohup and '&'. I understand that for the latter, if I want to kill it, I can just kill the process id. But for the former, can I just hit "CTRL+C" to kill the script. So if I were to run the below command
nohup sh script.sh
and then exit out of it by hitting "CTRL+C", will that script still be running or not?
It would be better if you would understand what's going on.
nohup
set's the process to ignore HUP
signal. That's all. Nothing more nothing less. When does a process receive a HUP
signal? Usually when a terminal logouts. And the default action on HUP
signal is to terminate.
hitting "CTRL+C"
just sends INT
signal to the process. The default action (and you can trap "echo something" INT
override it too) is to terminate the process.
nohup sh script.sh
upon receiving INT
signal will terminate (assuming script.sh
didn't specially handle the INT
signal) as it didn't set up a custom action on receiving a INT
signal and it will ignore HUP
signal.
The &
placed after a command runs it in the background. As a separate process. So sh script.sh &
runs sh
in the background. The process will still terminate if you send it INT
signal, just CTRL+C
doesn't send it to that process, but to process that is in foreground. You can send it still using kill
command. And the command will still terminate when the terminal exits, when the process receives the HUP
signal.
So running nohup sh script.sh &
will run the process in the background and ignore the signal that is send when the terminal exits. But still it will terminate on receiving INT
signal. Just pressing CTRL+C
in terminal will not send it to this process, as shell sends the term signal to the foreground process, not the background one.