Linux nohup and exec
nohup
and exec
commands do different things.
exec
replaces the shell with another program keeping the same PID. Usingexec
in a simple background job isn't useful:exec myprogram; more stuff
replaces the shell withmyprogram
and so doesn't runmore stuff
, unlikemyprogram; more stuff
which runs more stuff whenmyprogram
terminates; butexec myprogram & more stuff
startsmyprogram
in the background and then runs more stuff, just likemyprogram & more stuff
.
nohup
runs the specificed program with the SIGHUP signal ignored. When a terminal is closed, the kernel sends SIGHUP to the controlling process in that terminal (i.e. the shell). The shell in turn sends SIGHUP to all the jobs running in the background. Running a job withnohup
prevents it from being killed in this way if the terminal dies (which happens e.g. if you were logged in remotely and the connection drops, or if you close your terminal emulator).
nohup
also redirects the program's output to the filenohup.out
. This avoids the program dying because it isn't able to write to its output or error output. Note that nohup doesn't redirect the input. To fully disconnect a program from the terminal where you launched it, use
nohup myprogram </dev/null >myprogram.log 2>&1 &
exec
command explanation 2
In example exec firefox
, the shell is no longer running: it has been replaced by firefox
. You can think of exec
as combining exiting a program and starting a new one, but keeping the same process ID. The terminal keeps running because nothing told it to stop. When you later exit Firefox, the firefox process terminates. The terminal notices that its child process has exited and so it exits in turn.
exec &
- executes a process as a background process so you may continue using the same terminal for other jobs.nohup
- avoids all SIGHUP(terminate signal) and continues execution even if you terminal is closed.exec
- process dies when a SIGHUP is received, but nohup process continues.
nohup
command - explanation 2
nohup
is a Unix command that is used to run another command while suppressing the action of the HUP (hangup) signal, enabling the command to keep running after the user who issues the command has logged out. It is most often used to run commands in background as daemons. Output that would normally go to the terminal goes to a file called nohup.out if it has not already been redirected.
Run a script with nohup command:
$ nohup ~/utils/backup "upload" &
The HUP
signal is sent to a process when its controlling terminal is closed. It was originally designed to notify the process of a serial line drop (HUP stands for "Hang Up"). In modern systems, this signal usually means that the controlling pseudo or virtual terminal has been closed
References
- Why use “nohup &” rather than “exec &” unix.stackexchange.com