Advanced Shell Topics: Job/Process control


Job control refers to a user's ability to control whether a process executed from the shell is in the foreground, or has been backgrounded.

The difference here between foreground and background is somewhat simular to the difference between an application and a daemon. From the invokation point of view that is. When you start a process it usually prevents you from further using the shell until the program has finished. You may know however that you can background nearly any process upon starting it by using the amperstand character at the end of the command:

[user@host ~]$ tail -fn 0 /var/log/httpd/access_log &
[1] 12197
[user@host ~]$ jobs
[1]+  Running                 tail -fn 0 /var/log/httpd/access_log &
[user@host ~]$

So using the amperstand at the end of the tail command put the process in the background. Note that tail is still running and would still produce output on stdout. The jobs command that we ran secondly shows what processes are in the background.

To bring the most recently backgrounded process back to the foreground, you can use fg with no arguemnts:

[user@host ~]$ fg
tail -fn 0 /var/log/httpd/access_log

Notice that it brought it back without giving a shell prompt afterwards, this is just like what would happen if you hadn't backgrounded the process at all when running tail.

When backgrounding multiple processes, it is nesecary to refer to the job number (number in brackets) when bringing a non-recent job to the foreground.

[user@host ~]$ tail -fn0 /var/log/httpd/error_log &
[1] 12205
[user@host ~]$ find / -name '*.au' &
[2] 12209
[user@host ~]$ play rms.au &
[3] 12214
[user@host ~]$ jobs
[1]   Running                 tail -fn 0 /var/log/httpd/error_log &
[2]-  Running                 find / -name '*.au' &
[3]+  Running                 play rms.au &
[user@host ~]$ fg %1
tail -fn 0 /var/log/httpd/error_log

If you've started a process in the foreground and you decide later that you'd like to background the process you can use the Ctrl-z sequence to stop the process and then use %& on the command line to restart the process in the background.

[root@host ~]# tar zxf linux-3.5.17.tar.gz   [Process stays in foreground on execution]
(Ctrl-z)
[1]+  Stopped                 tar zxf linux-3.5.17.tar.gz
[root@host ~]# %&
[1]+ tar zxf linux-3.5.17.tar.gz &
[root@host ~]# jobs
[1]+  Running                 tar zxf linux-3.5.17.tar.gz &
[root@host ~]# 

Ctrl-z can also be useful when you are running session-based programs like pine, vi, emacs and you wish to break out to the shell to do something. While in any of these programs just use Ctrl-z and it will give you the following indication that the program has stopped:

[1]+  Stopped                 emacs -nw
[suso@suso ~]$

You can then do what you need to do in other programs before using the 'fg' command to return back to the program that was stopped from your Ctrl-z.


© 2000 Suso Banderas - suso@suso.org