Why use "nohup &" rather than "exec &"

  • I know that, nohup being a binary, it can be reached from any shell. But the exec built-in probably exists in every shell.

    Is there a reason to prefer one of them, to the other?

  • What's better, a fish or a bicycle? nohup and exec do different things.

    exec replaces the shell with another program. Using exec in a simple background job isn't useful: exec myprogram; more stuff replaces the shell with myprogram and so doesn't run more stuff, unlike myprogram; more stuff which runs more stuff when myprogram terminates; but exec myprogram & more stuff starts myprogram in the background and then runs more stuff, just like myprogram & 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 with nohup 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 file nohup.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 &

    a bicycle > a fish

    I beg to differ. Fish is obviously a superior method of transportation if it can be implemented.

    @THISUSERNEEDSHELP But a bicycle is better food, surely?

    By testing I saw that when I ran `exec firefox` and then closed `firefox`, it also closed my shell. I understood what nohup does but I don't understand what you mean when you say `exec` replaces the `shell` with the `` ?

    @GypsyCosmonaut After you run `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.

    Give a man a fish and you feed him for a day. Give a man a bicycle and he can ride it to the supermarket and buy fish for a lifetime.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM