Job Control

To distinguish them from system processes, the commands that users

execute from a shell or a script file are often called "jobs". This

week, I will show you how a set of job control operations can allow the

user to control the execution of such jobs from the command shell.

Background Execution

Placing an ampersand at the end of the command executes a job in the

background. The system assigns each user's job a unique number in

addition to a PID. When you execute a command in the background, a

user's job number and a system process id appear on the screen. For

example:

$ lpr payroll &

[1] 236

$

The number in brackets is the user's job id; the second number is the

system process's PID. You can place multiple commands in the background

at once by separating each command with an ampersand. For example:

$ lpr july & cat *.c &

The "jobs" command lists the current background jobs. Jobs displays

each entries' job number in brackets, whether it's stopped or running,

and its name:

$ jobs

[1] + Running lpr july

[2] - Running cat *.c

A plus sign indicates that the job is currently being processed. A

minus sign indicates the next job to be executed.

Notification

By default, Linux doesn't interrupt other operations, say an editing

session, to notify you that a certain job has completed. If you wish to

be notified on a job's completion, then use the "notify" command.

Notify takes a job number preceded by a percent sign as its argument:

$ notify %2

This will cause the system to notify you when job 2 has completed,

regardless of your current activity.

Switching between Background and Foreground

You can bring a background job to the foreground by executing the "fg"

command. If there are several background jobs, then you must indicate

which job you wish to move to the foreground by indicating its job

number:

$ fg %2

Likewise, you can move a currently running foreground job to the

background with the "bg" command. In order to do that, you first need

to suspend the job by pressing CTRL-Z. Then issue the bg command to

resume the suspended job's execution in the background. For example:

$ lpr july

^Z

$ bg

Killing a Job

To cancel a running job, use the "kill" command. kill takes a PID or a

job number preceded by % as its argument. In the following example, the

user examines the currently running jobs and cancels job 2:

$ jobs

[1] + Running lpr july

[2] - Running cat *.c

$ kill %2

$

Free Course: JavaScript: The Good Parts
View Comments
You Might Like
Join the discussion
Be the first to comment on this article. Our Commenting Policies