Process Groups, Sessions, and Job Control 715
Each job that is placed in the background is assigned a unique job number by the
shell. This job number is shown in square brackets after the job is started in the
background, and also when the job is manipulated or monitored by various job-
control commands. The number following the job number is the process ID of the
process created to execute the command, or, in the case of a pipeline, the process
ID of the last process in the pipeline. In the commands described in the following
paragraphs, jobs can be referred to using the notation %num, where num is the
number assigned to this job by the shell.
In many cases, the %num argument can be omitted, in which case the current
job is used by default. The current job is the last job that was stopped in the
foreground (using the suspend character described below), or, if there is no
such job, then the last job that was started in the background. (There are some
variations in the details of how different shells determine which background job
is considered the current job.) In addition, the notation %% or %+ refers to the
current job, and the notation %– refers to the previous current job. The current
and previous current jobs are marked by a plus (+) and a minus (–) sign, respec-
tively, in the output produced by the jobs command, which we describe next.
The jobs shell built-in command lists all background jobs:
$ jobs
[1]- Running grep -r SIGHUP /usr/src/linux >x &
[2]+ Running sleep 60 &
At this point, the shell is the foreground process for the terminal. Since only a fore-
ground process can read input from the controlling terminal and receive terminal-
generated signals, sometimes it is necessary to move a background job into the
foreground. This is done using the fg shell built-in command:
$ fg %1
grep -r SIGHUP /usr/src/linux >x
As demonstrated in this example, the shell redisplays a job’s command line whenever
the job is moved between the foreground and the background. Below, we’ll see
that the shell also does this whenever the job’s state changes in the background.
When a job is running in the foreground, we can suspend it using the terminal
suspend character (normally Control-Z), which sends the SIGTSTP signal to the termi-
nal’s foreground process group:
Type Control-Z
[1]+ Stopped grep -r SIGHUP /usr/src/linux >x
After we typed Control-Z, the shell displays the command that has been stopped in
the background. If desired, we can use the fg command to resume the job in the
foreground, or use the bg command to resume it in the background. In both cases,
the shell resumes the stopped job by sending it a SIGCONT signal.
$ bg %1
[1]+ grep -r SIGHUP /usr/src/linux >x &