The Linux Programming Interface

(nextflipdebug5) #1

716 Chapter 34


We can stop a background job by sending it a SIGSTOP signal:
$ kill -STOP %1
[1]+ Stopped grep -r SIGHUP /usr/src/linux >x
$ jobs
[1]+ Stopped grep -r SIGHUP /usr/src/linux >x
[2]- Running sleep 60 &
$ bg %1 Restart job in background
[1]+ grep -r SIGHUP /usr/src/linux >x &
The Korn and C shells provide the command stop as a shorthand for kill –stop.
When a background job eventually completes, the shell prints a message prior to
displaying the next shell prompt:
Press Enter to see a further shell prompt
[1]- Done grep -r SIGHUP /usr/src/linux >x
[2]+ Done sleep 60
$

Only processes in the foreground job may read from the controlling terminal. This
restriction prevents multiple jobs from competing for terminal input. If a back-
ground job tries to read from the terminal, it is sent a SIGTTIN signal. The default
action of SIGTTIN is to stop the job:
$ cat > x.txt &
[1] 18947
$
Press Enter once more in order to see job state changes displayed prior to next shell prompt
[1]+ Stopped cat >x.txt
$
It may not always be necessary to press the Enter key to see the job state
changes in the previous example and some of the following examples.
Depending on kernel scheduling decisions, the shell may receive notification
about changes in the state of the background job before the next shell prompt
is displayed.
At this point, we must bring the job into the foreground (fg), and provide the
required input. If desired, we can then continue execution of the job in the back-
ground by first suspending it and then resuming it in the background (bg). (Of
course, in this particular example, cat would immediately be stopped again, since it
would once more try to read from the terminal.)
By default, background jobs are allowed to perform output to the controlling
terminal. However, if the TOSTOP flag (terminal output stop, Section 62.5) is set for the
terminal, then attempts by background jobs to perform terminal output result in
the generation of a SIGTTOU signal. (We can set the TOSTOP flag using the stty com-
mand, which is described in Section 62.3.) Like SIGTTIN, a SIGTTOU signal stops the job.
$ stty tostop Enable TOSTOP flag for this terminal
$ date &
[1] 19023
$
Press Enter once more to see job state changes displayed prior to next shell prompt
[1]+ Stopped date
Free download pdf