2

What exactly does it mean to run a process in the background?

The difference between $program and $program&: Is it just that the input file descriptor is not inherited from the shell or is there something else / something more?

Toby Speight
  • 8,678
Lavya
  • 1,605

3 Answers3

3

program & will still have the same stdin and stdout as program, but program & usually (depending on your terminal settings) won't be able to read from stdin without getting stopped by the system via the SIGTTIN signal (see https://en.wikipedia.org/wiki/Job_control_(Unix)#Implementation ).

Background processes won't receive signals from keyboard shortcuts (Ctrl-C, Ctrl-\, Ctrl-Z) and of course, running processes in the background will let you keep using the shell (e.g., to start additional processes).

Petr Skocik
  • 28,816
1

It means a number of things.

  1. The backgrounded process is not holding up your terminal. It is being run "asynchronously" in that we are not waiting for it to complete. It will still die if disconnection is forced.
  2. Consequently the responses are not necessarily "active" but "passive", it is good form to redirect output to a file for later inspection.
  3. Interactive input is going to be problematic unless a batch solution (command file or response file or expect) is considered.
  4. For "long running" jobs, you may want to consider starting as a service.
  5. See also tmux and screen for alternatives if backgrounding is problematic.
mckenzm
  • 327
0

When you start a process in the foreground, the shell will wait for it to complete (with one of the wait() family of system calls) before reading the next command. When you start a process in the background, the shell does not wait for it to complete or change state; it immediately reads and executes the next command.

Note that whether or not you start a process in the background, you can move it between background and foreground at will (with ^Z and bg, or with fg). All jobs are equal in that respect. The only restriction is that there can be at most one foreground job at any given time, and backgrounded jobs get stopped if they try to use the shell's tty.

Whenever there is no foreground job, the shell will read its next command (from the script file or from stdin) and execute it.

Toby Speight
  • 8,678