home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book HomeRunning LinuxSearch this book

4.11. Putting a Command in the Background

Before the X Window System, which made it easy to run multiple programs at once, Unix users took advantage of Unix's multitasking features by simply putting an ampersand at the end of commands, as shown in this example:

$ gcc invinitjig.c & 
[1] 21457

The ampersand puts the command into the background, meaning that the shell prompt comes back, and you can continue to execute other commands while the gcc command is compiling your program. The [1] is a job number that is assigned to your command. The 21457 is a process ID, which we'll discuss later. Job numbers are assigned to background commands in order and therefore are easier to remember and type than process IDs.

Of course, multitasking does not come for free. The more commands you put into the background, the slower your system runs as it tries to interleave their execution.

You wouldn't want to put a command in the background if it requires user input. If you do so, you see an error message like:

Stopped (tty input)

You can solve this problem by bringing the job back into the foreground through the fg command. If you have many commands in the background, you can choose one of them by its job number or its process ID. For our long-lived gcc command, the following commands are equivalent:

$ fg %1 
$ fg 21457

Don't forget the percent sign on the job number; that's what distinguishes job numbers from process IDs.

To get rid of a command in the background, issue a kill command:

$ kill %1

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.