January 03, 2004

Jobs control in unix

Some simple assumptions: the syntax is for the C-shell (csh or tcsh), not bash or sh. sudo is a command that calls a program as root.

If one wants to send a job to the background in Unix, most people know that you append '&' to the command:

% sudo /usr/libexec/locate.updatedb &

It is in the background, as you can see with the command:

% jobs -l [1] + 23035 Running sudo /usr/libexec/locate.updatedb

[1] is the job number ([1], [2], [3], etc...). Don't confuse the job number with the PID 23035 (Process ID number). You can bring the job back to the foreground with fg %1 (or just fg):


% fg

But what do you do when you have the job in the foreground and you want to send it to the background (i.e. you are "stuck" because you forgot the &, or you simply changed your mind and now you want the job in the background)? Ctrl-C will kill the job, and you don't want that. If you type Control-Z, the job gets "suspended" which means, it is in not in the foreground anymore, but it is not running either. For instance if you type:

% sudo /usr/libexec/locate.updatedb

then Control-Z, the shell will respond with:

^Z Suspended

Listing the jobs will give you the following:

% jobs -l [1] + 23039 Suspended sudo /usr/libexec/locate.updatedb

To make it run again, you have two options: use the bg command (which means "make it RUN in the background" or "change its status from suspended to running):

% bg

Also, and that I did not know until recently, you can use kill -CONT <pid>, where <pid> is the process id number. In this context, kill is actually a pretty bad command name: it does not "kill" the program. It sends a signal to the program (which, if you don't use -CONT(inue), will be by default -TERM(inate)). Similarly, you can send a -STOP signal to suspend a job that is already in the background.

For instance, if you are running a lengthy and CPU consuming job (or disk consuming job), like:

% sudo /usr/libexec/locate.updatedb & [1]

You can see it running in the background:

% jobs -l [1] + 21035 Running sudo /usr/libexec/locate.updatedb

where [1] is the job number and 21035 is the pid. By issuing:

% kill -STOP 21035

you will suspend the job, until you use the bg command with the job number, or kill -CONT with the process ID number.

Posted by dccote at January 3, 2004 11:46 PM
Comments