Shell – Where do background jobs go

background-processjob-controljobsshell

From gnome-terminal I know the ability to suspend a job with C-z, and then send it to the background. When I close the terminal the process does not end. Where is the job being managed from, or is it lost?

Best Answer

Your background job continues executing until someone tells it to stop by sending it a signal. There are several ways it might die:

  • When the terminal goes away for any reason, it sends a HUP signal (“hangup”, as in modem hangup) to the shell running inside it (more precisely, to the controlling process) and to the process in the foreground process group. A program running in the background is thus not affected, but…
  • When the shell receives that HUP signal, it propagates it to the background jobs. So if the background process is not ignoring the signal, it dies at this point.
  • If the program tries to read or write from the terminal after it's gone away, the read or write will fail with an input/output error (EIO). The program may then decide to exit.
  • You (or your system administrator), of course, may decide to kill the program at any time.

If your concern is to keep the program running, then:

  • If the program may interact with the terminal, use Screen or Tmux to run the program in a virtual terminal that you can disconnect from and reconnect to at will.
  • If the program just needs to keep running and is not interactive, start it with the nohup command (nohup myprogram --option somearg), which ensures that the shell won't send it a SIGHUP, redirects standard input to /dev/null and redirects standard output and standard error to a file called nohup.out.
  • If you've already started the program and don't want it to die when you close your terminal, run the disown built-in, if your shell has one. If it doesn't, you can avoid the shell's propagation of SIGHUP by killing the shell with extreme prejudice (kill -KILL $$ from that shell, which bypasses any exit trigger that the indicated process has).
  • If you've already started the program and would like to reattach it to another terminal, there are ways, but they're not 100% reliable. See How can I disown a running process and associate it to a new screen shell? and linked questions.
Related Question