If you're using the Bourne shell, you have to watch out for putting a series of commands separated by semicolons ( 8.5 ) into the background. The Bourne shell puts only the last command on the line into the background, but waits for the first.
An easy way to test this is with the following command line, which waits for 15 seconds, then does an ls :
$sleep 15; ls &
In the Bourne shell, you won't get your prompt back until the sleep ( 40.2 ) command has finished.
The proper way to put a series of Bourne shell commands into the background is to group them with parentheses:
( ) |
$
|
---|
This may strike you as a defect, but in fact, it's a sign of the greater precision of Bourne shell syntax, which makes it somewhat exasperating for interactive use, but much better for programming.
It doesn't make any sense to run an interactive program such as an editor in the background. For example, if you type this from the C shell:
%vi &
[1] 3071
you'll get a message like the following:
[1] + Stopped (tty output) vi
vi can be active only in the foreground. However, it does make sense to have vi stopped ( 12.8 ) in the background.
If you are running vi or any other interactive program, you can quickly get back to the shell by typing CTRL-z to stop the program. The shell will take control of your terminal and print another shell prompt.
Stopping
vi
(
12.4
)
is more efficient than using its
shell escape mechanism (
30.26
)
, since it lets you go back to your original shell rather than starting a new one. Simply type
fg
to get back to where you were in editing.
We have shared a system with new users who were overenthusiastic users of background processes, rather like the man who loved loving so much he sought many lovers. Because each background process is competing for the same resources, running many of them can be a drain on the system. This means that everything takes longer for everyone. We used to have people who thought that if they ran three troff ( 43.13 ) processes at once, they'd get their three files formatted faster than if they did them one after another. Boy, were they mistaken. [4]
[4] In the old days, UNIX systems gave all processes to a single CPU. Modern UNIX systems can have multiple CPUs. On these systems, you may do several jobs almost as quickly as one.
If you use the Bourne shell, any background processes you have running will normally be terminated when you log out. To avoid this, use the nohup ( 38.18 ) command.
Not all processes are created equal. UNIX maintains a queue of processes ordered by priority. Foreground processes, such as a user typing a command at a prompt, often receive higher priority than background processes. However, you may want to run background processes at an even lower priority, by using nice ( 39.9 ) . This is a relatively painless way of being kind to other users - and making your foreground job run faster - though it will make your background tasks take a little longer.
-
,