7.1 Running a Command in the Background


Running a program as a background process is most often done to free a Terminal when you know the program will take a long time to run. It's also used whenever you want to launch a new application from an existing Terminal window ”so that you can keep working in the existing Terminal, as well as within the new application.

To run a program in the background, add the & character at the end of the command line before you press the Return key. The shell then assigns and displays a process ID number for the program:

 $  sort bigfile > bigfile.sort &  [1] 372 $ 

Sorting is a good example because it can take a while to sort huge files.

The process ID (PID) for this program is 372. The PID is useful when you want to check the status of a background process, or if you need to cancel it. To check on the status of the process, use ps -up PID ; if you want to cancel a process, use kill PID . In this instance, these commands would look like:

 $  ps -up 372  USER     PID %CPU %MEM      VSZ    RSS  TT  STAT STARTED      TIME COMMAND taylor   372   0.0  0.0    18208    340 std  S    10:56PM   0:00.04 sort $  kill 372  $ 

Fortunately, you don't need to remember the PID every time, because there are Unix commands (explained in the next section) to check on the processes you have running. Also, bash writes a status line to your screen when the background process finishes.

In bash , you can put an entire sequence of commands separated by semicolons ( ; ) into the background by putting an ampersand ( & ) at the end of the entire command line. In other shells , enclose the command sequence in parentheses before adding the ampersand:

 (   command1; command2   ) & 

Mac OS X Unix shells also have a feature (mentioned earlier) called job control . You can use the suspend character (usually Control-Z) to suspend a program running in the foreground. The program pauses, and you get a new shell prompt. You can then do anything else you like, including putting the suspended program into the background using the bg command. The fg command brings a suspended or background process to the foreground.

For example, you might start sort running on a big file, and, after a minute, want to edit a file. Stop sort , then put it in the background. The shell prints a message, and then another shell prompt, at which you can enter your vi command while sort runs.

 $  sort hugefile1 hugefile2 > sorted  ...time goes by...  CTRL-Z  Stopped $  bg  [1]    sort hugefile1 hugefile2 > sorted & $  vi test.txt  


Learning Unix for Mac OS X Panther
Learning Unix for Mac OS X Panther
ISBN: 0596006179
EAN: 2147483647
Year: 2003
Pages: 88

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net