Background I/O

Jobs you put in the background should not do I/O to your terminal. Just think about it for a moment and you'll understand why.

By definition, a background job doesn't have control over your terminal. Among other things, this means that only the foreground process (or, if none, the shell itself) is "listening" for input from your keyboard. If a background job needs keyboard input, it will often just sit there doing nothing until you do something about it (as described in Chapter 8).

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

If a background job produces screen output, the output will just appear on your screen. If you are running a job in the foreground that produces output too, then the output from the two jobs will be randomly (and often annoyingly) interspersed.

If you want to run a job in the background that expects standard input or produces standard output, you usually want to redirect the I/O so that it comes from or goes to a file. Programs that produce small, one-line messages (warnings, "done" messages, etc.) are an exception to this general rule; you may not mind if these are interspersed with whatever other output you are seeing at a given time.

For example, the diff utility examines two files, whose names are given as arguments, and prints a summary of their differences on the standard output. If the files are exactly the same, diff is silent. Usually, you invoke diff expecting to see a few lines that are different.

diff, like sort and compress, can take a long time to run if the input files are very large. Suppose that you have two large files that are called warandpeace.txt and warandpeace.txt.old. The command diff warandpeace.txt warandpeace.txt.old [15] reveals that the author decided to change the name "Ivan" to "Aleksandr" throughout the entire file—i.e., hundreds of differences, resulting in very large amounts of output.

If you type diff warandpeace.txt warandpeace.txt.old &, then the system will spew lots and lots of output at you, which will be difficult to stop—even with the techniques explained in Chapter 7. However, if you type:

$ diff warandpeace.txt warandpeace.txt.old > txtdiff &

then the differences will be saved in the file txtdiff for you to examine later.