Chapter 8: Processes

Jobs and the background

A terminal can run one thing at a time in the foreground, and the prompt only comes back when it finishes. Job control lets you start commands in the background, pause them, and bring them back, all from one terminal.

Foreground and background

A job is a process (or pipeline) started from your shell. The foreground job owns the terminal: it receives your keystrokes, and the prompt waits. A background job runs without the terminal, and the prompt is free for the next command.

Add & to start a command in the background. The shell prints its job number in brackets, then its PID:

[student@servera ~]$ sleep 500 &
[1] 762
[student@servera ~]$ sleep 501 &
[2] 763
[student@servera ~]$ jobs
[1]-  Running                 sleep 500 &
[2]+  Running                 sleep 501 &

The + marks the "current" job (the default for fg and bg), and - the previous one. jobs -l adds the PIDs. Job numbers belong to your shell: another terminal has its own list. They are not PIDs. Refer to a job with a percent sign: %1, %2, or %% for the current one.

Moving jobs around

Step through the life of a job:

The life of a job: Step through starting, pausing and resuming a command in your terminal.

The keys and commands that drive it:

Do thisTo
Ctrl+CInterrupt (stop for good) the foreground job
Ctrl+ZPause (stop) the foreground job
bg %NContinue a stopped job in the background
fg %NBring a job to the foreground
kill %NTerminate a job
[student@servera ~]$ fg %1
sleep 500
^Z
[1]+  Stopped                 sleep 500
[student@servera ~]$ bg %1
[1]+ sleep 500 &
[student@servera ~]$ kill %2
[2]+  Terminated              sleep 501

A background job still writes to the terminal if it prints anything, which can interleave with what you are typing. Redirect its output (cmd > out.txt 2>&1 &) when it is chatty.

Surviving a logout

When a terminal window closes or a connection drops, the shell receives SIGHUP ("hangup") and passes it on to its jobs, and most programs end. (Simply typing exit does not do this: the shell leaves its background jobs running.) Two ways to protect a job:

[student@servera ~]$ nohup sleep 700 &
[3] 766
nohup: ignoring input and appending output to 'nohup.out'

Try it

Check your understanding