1. Trang chủ
  2. » Công Nghệ Thông Tin

UNIX UNLEASHED PHẦN 4 pps

60 147 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Process Control in UNIX
Tác giả Rachel, Robert Sartin
Trường học University of Example
Chuyên ngành Computer Science
Thể loại Thesis
Thành phố Sample City
Định dạng
Số trang 60
Dung lượng 487,17 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

 Checking the Aliases and Built-Ins  Make a New Process with fork  Start a New Command with exec  An Example  Executing in the Background  An Example  Kinks in Your Pipelin

Trang 1

Part IV — Process Control

What Is a Process?

Administering Processes

Scheduling Processes

 18 – What Is a Process?

 By Rachel and Robert Sartin

 What Happens When You Execute a Command?

 Checking the Aliases and Built-Ins

 Make a New Process with fork

 Start a New Command with exec

 An Example

 Executing in the Background

 An Example

 Kinks in Your Pipeline

 A Special Process Called Daemon

By Rachel and Robert Sartin

This chapter introduces the concept of processes and how you use UNIX to interact with them

What Happens When You Execute a Command?

Trang 2

When you execute a program on your UNIX system, the system creates a special

environment for that program This environment contains everything needed for the system to run the program as if no other program were running on the system

Forking a Process

Each process has process context, which is everything that is unique about the state of the program you are currently running The process context includes then following:

 The text (program instructions) being run

 The memory used by the program being run

 The current working directory

 The files that are open and positions in the files

 Resource limits

 Access control information

 Others—various low-level information

Every time you execute a program the UNIX system does a fork, which performs a series

of operations to create a process context and then execute your program in that context The steps include the following:

1 Allocate a slot in the process table, a list of currently running programs kept by UNIX UNIX creates the illusion of multiple programs running simultaneously by switching quickly between active processes in the process table This allocation can fail for a number of reasons, including these:

o You have exceeded your per user process limit, the maximum number of processes your UNIX system will allow you to run

o The system runs out of open process slots The UNIX kernel stores

information about currently running processes in a table of processes When this table runs out of room for new entries, you are unable to fork a new process

o UNIX has run out of memory and does not have room for the text and data

of the new process

2 Assign a unique process identifier (PID) to the process This identifier can be used

to examine and control the process later

3 Copy the context of the parent, the process that requested the spawning of the new process

Trang 3

4 Return the new PID to the parent process This enables the parent process to examine or control the process directly

After the fork is complete, UNIX runs your program One of the differences between UNIX and many other operating systems is that UNIX performs this two-step procedure

to run a program The first step is to create a new process that's just like the parent The second is to execute a different program This procedure allows interesting variations (See the section "A Special Process Called Daemon.")

3 The ls program is loaded into the new process context, replacing the text and data

Different versions of ps do similar things, but have somewhat different output and are controlled using different options The X/Open Portability Guide makes an attempt to standardize somewhat on output of the ps command The ps command is covered in more detail in chapter 19, "Administrative Processes."

On a System V or XPG-compliant system, you can examine all the processes you are running by entering ps -f and you will get output such as the following:

$ ps -f

UID PID PPID C STIME TTY TIME COMMAND

root 14931 136 0 08:37:48 ttys0 0:00 rlogind

sartin 14932 14931 0 08:37:50 ttys0 0:00 -sh

Trang 4

sartin 15339 14932 7 16:32:29 ttys0 0:00 ps -f

$

NOTE: After the first line, which is the header, each line of output tells about the

status of a single process The UID column tells the owner of the process The PID

column tells the process ID The PPID tells the process ID of the parent process (the process that executed the fork) The STIME is the time the process began executing The TIME is the amount of computer time the process has used The COMMAND field tells what command line was executed

Look at this example and you can see that root (the system administration user) is

running rlogind as process 14931 This process is a special kind of administrative

program, called a daemon (daemons are described in the section "A Special Process Called Daemon") This particular daemon is responsible for managing a connection from rlogin, which is described in Chapter 8, "Getting Around the Network." As you can see from the next line, there is a process called -sh, which is a Bourne shell The shell has rlogind as its parent because the daemon did a fork to run the login shell Similarly, there

is a ps -f command that has the shell as its parent

TIP: The leading hyphen on the -sh in the output of ps means that the shell is

executing as a login shell, which does certain special processing that other instances of the shell do not See the chapter on your shell for more information on login shells

Visiting the Shell Again

Earlier in this chapter you learned that the shell creates a new process for each command you execute This section covers in a bit more detail how the shell creates and manages processes

Processing a Command

When you type a command to your shell user interface, the shell performs a series of tasks to process the command Although the steps may seem a bit cumbersome at first, they create an environment that is highly flexible

Checking the Aliases and Built-Ins

Trang 5

The first thing the shell does is alias and built-in processing to see if your command is one of the shell's internally implemented functions Each shell implements a number of functions internally either because external implementation would be difficult (for example, while loops) or because internal implementation is a big performance win (for example, echo in some shells) One reason the built-in commands are easier is that they can operate directly in the shell process rather than forcing the shell to create a new process to run a different command That new command would not have access to the shell's memory

Make a New Process with fork

If the command you typed is not a built-in command (for example, if you entered ps), the shell performs a fork to create a new process Your UNIX system allocates the necessary resources The shell modifies the process environment to configure correctly for the command to be executed This includes any input or output redirect you may have

requested (including command pipelines) and creating a new background process group

if you executed the command in the background

Start a New Command with exec

Finally, the shell performs an exec to execute the program that you requested The

program will replace the shell with a forked shell, but your shell will still be running

An Example

The following happens when you enter ps -f > t1 followed by cat t1:

$ ps -f > t1

$ cat t1

UID PID PPID C STIME TTY TIME COMMAND

root 14931 136 0 08:37:48 ttys0 0:00 rlogind

sartin 14932 14931 0 08:37:50 ttys0 0:00 -sh

sartin 15339 14932 7 16:32:29 ttys0 0:00 ps -f

$

UNIX performs the following steps to execute ps -f> t1:

1 Shell command processing The login shell (PID 14932 in this example)

performs variable substitution and examines the command line to determine that

ps is not a built-in or an alias

2 fork/wait The login shell (PID 14932) forks a new process (PID 15339) This

new process is an exact copy of the login shell It has the same open files, the

Trang 6

same user ID, and a copy of the memory, and it is executing the same code

Because the command was not executed in the background, the login shell

(14932) will execute a wait to wait for the new child (15339) to complete

3 setup The new shell (PID 15339) performs the operations it needs to do in order

to prepare for the new program In this case, it redirects the standard output to a file (if it existed) in the current directory named t1, overwriting the file

4 exec The new shell (PID 15339) asks the UNIX system to exec the ps command

with -f as its argument UNIX throws away the memory from the shell and loads the ps command code and data into the process memory The ps command will run and write its output to the standard output, which has been redirected to the file t1

5 wait ends When the ps command is done executing, the login shell (PID 14932)

receives notification and will prompt the user for more input

Executing in the Background

You can tell your shell to execute commands in the background, which tells the shell not

to wait for the command to complete This enables you to run programs without having to wait for them to complete

TIP: For long-running commands that are not interactive, you can run the

command in the background and continue to do work while it executes Use the nohup command to make sure the process will not get interrupted; nohup will redirect the

command output to a file called nohup.out For example, to run a make in the background enter nohup make all When the make terminates, you can read nohup.out to check the output

An Example

This example is almost the same as the previous example The only difference is that the

ps command is executed in the background The following happens when you are using the Bourne shell and enter ps -f > t1 & followed by cat t1:

Trang 7

root 14931 136 1 08:37:48 ttys0 0:00 rlogind

sartin 14932 14931 0 08:37:50 ttys0 0:00 -sh

sartin 15445 14932 8 17:31:14 ttys0 0:00 ps -f

$

WARNING: Do not depend on the output of a background process until you know

the process has completed If the command is still running when you examine the output, you may see incomplete output

UNIX performs the following steps to execute ps -f > t1 &:

1 Shell command processing The login shell (PID 14932 in this example)

performs variable substitution and examines the command line to determine that

ps is not a built-in or an alias

2 fork The login shell (PID 14932) forks a new process (PID 15445) This new

process is an exact copy of the login shell It has the same open files, the same user ID, and a copy of the memory, and it is executing the same code Because the command was executed in the background, the login shell (14932) will

immediately prompt you for input Because your background command may still

be running, you should not depend on its output until you know the process

completed You will be able to run a new command immediately

3 setup The new shell (PID 15445) performs the operations it needs to do in order

to prepare for the new program In this case, it redirects the standard output to a file in the current directory named t1, overwriting the file (if it existed)

4 exec The new shell (PID 15445) asks the UNIX system to exec the ps command

with -f as its argument UNIX throws away the memory from the shell and loads the ps command code and data into the process memory The ps command will run and write its output to the standard output, which has been redirected to the file t1

Kinks in Your Pipeline

One of the things the fork/exec model enables is creating command pipelines, a series of commands with the output of one command as the input for the next This powerful notion is one of the major advantages of UNIX over some other systems See Chapter 1,

"Operating Systems."

Creating a pipeline is similar to creating an ordinary command The difference is in how output is redirected In the ordinary case, the shell performs some simple I/O redirection

Trang 8

before executing the program In the pipeline case, the shell will instead connect the standard output of one command as the standard input of another

If you enter ps -f | grep sartin you might get output such as the following:

NOTE: Some shells perform these tasks in slightly different orders This example

illustrates what one version of the Bourne shell does Variations are relatively minor and involve the details of which process does the extra fork calls

In order to get this output, the shell went through the following series of steps:

1 fork (1) The login shell (PID 14932) forks a new process (15424) to execute the

pipeline This subprocess (15424) redirects input, or creates a pipe, so that

standard input is from a pipe The login shell (14932) then waits for the pipeline execution to complete

2 fork (2) The shell subprocess (15424) forks another new process (15425) to help

execute the pipeline This new subprocess (15425) connects its standard output to the pipe that its parent (15424) is using for input

3 exec (1) The first subprocess (15424) executes the grep program

4 exec (2) The second subprocess (15425) executes the ps program

Avoiding the Background with GUI

With the advent of graphical user interfaces (GUIs) on UNIX, you do not need to use background processes to be able to run multiple programs at once Instead, you can run each command either from a graphical interface or from its own terminal window This can be very resource intensive, so don't try to do too many things at once

Trang 9

A Special Process Called Daemon

As you learned in Chapter 1, many of the features that are sometimes implemented as part of the kernel, the core of the operating system, are not in the UNIX kernel Instead, many of these features are implemented using special processes called daemons A

daemon is a process that detaches itself from the terminal and runs, disconnected, in the background, waiting for requests and responding to them Many system functions are commonly performed by daemons, including the sendmail daemon, which handles mail, and the NNTP daemon, which handles USENET news Many other daemons may exist

on your system; check the documentation for more information

Generally only system administrators need to know about most daemons, but there are three daemons that are important and widespread enough that you should probably have a minimal understanding of what they do; they are init, inetd, and cron

init

In a way the init program is the "super daemon." It takes over the basic running of the system when the kernel has finished the boot process It is responsible for the following:

Running scripts that change state Every time the system administrator switches

the system to a new state, init runs any programs needed to update the system to the new state

Managing terminals Each physical terminal is monitored by a program called

getty; it is the job of init to keep getty properly running and shut it down when the system administrator disables logins On systems with GUI consoles, init may be responsible for keeping the graphical login program running

Reaping processes When a process terminates, UNIX keeps some status

information around until the parent process reads that information Sometimes the parent process terminates before the child Sometimes the parent process

terminates without reading the status of the child Any time either of these

happens, UNIX makes init the parent process of the resulting zombie process, and init must read the process status so that UNIX can reuse the process slot

Sometimes, init isn't able to do the job of releasing zombies, too However, this is unusual in most of the recent UNIX-based systems

For further information on init, see Chapter 34, "Starting Up and Shutting Down."

inetd

A second powerful daemon is the inetd program common to many UNIX machines (including those based on BSD and many that are based on System V) The inetd process

is the network "super server" daemon It is responsible for starting network services that

do not have their own stand-alone daemons For example, inetd usually takes care of

Trang 10

incoming rlogin, telnet, and ftp connections (See Chapter 9, "Getting Around the

Summary

In this chapter you have learned what a UNIX process is, how your interaction with UNIX starts and stops processes, and a little bit about a few special processes called daemons A process is an entire execution environment for your computer program; it is almost like having a separate computer that executes your program UNIX switches quickly between processes to give the illusion that they are all running simultaneously You start a process any time you run a command or pipeline in the shell You can even start a process in the background and perform other tasks while it is executing Several processes called daemons run on your system to perform special tasks and supply

services that some operating systems supply in the kernel

 19 — Administering Processes

 By Rachel and Robert Sartin

 Monitoring Processes—ps and time

 What Is ps?

 Introduction to SYSV ps Output

 Introduction to BSD ps Output

 Checking on Your Processes with ps

 Everything You Own

 Specific Processes

 Specific Process Groups

 Specific Terminal

 Specific User

 Checking on a Process with time

 Background and Foreground Processes

 Foreground Processing

 Where Is the Background and Why Should You Go There?

Trang 11

 Job Control

 Signaling Processes

 Killing Processes

 The kill Command

 Finding What to Kill Using ps

 Determining Which Signal to Send

 The dokill Script An Example

 Logging Out with Background Processes

 Using nohup

 Prioritizing Processes

 What Is a Priority?

 Being Nice

 Using renice on a Running Process

 Job Control and Process Groups

 Using the jobs Command

 Putting Jobs in the Foreground

 Suspending Process Groups

 Putting Jobs in the Background

 Using wait to Wait for Background Jobs

 Using csh notify to Learn About Changes Sooner

 My System Is Slow—Performance Tuning

 Monitoring the System with ps

 Monitoring the System with sar

 Summary

19 — Administering Processes

By Rachel and Robert Sartin

You use processes on UNIX every time you want to get something done Each command (that isn't built into your shell) you run will start one or more new processes to perform your desired task To get the most benefit out of your UNIX machine you need to learn how to monitor and control the processes that are running on it You will need to know how to make large, but not time-critical, tasks take less of your CPU time You will need

to learn how to shut down programs that have gone astray You will need to learn how to improve the performance of your machine

Monitoring Processes—ps and time

The first step in controlling processes in UNIX is to learn how to monitor them By using the process-monitoring commands in UNIX, you will be able to find what programs are using your CPU time, find jobs that are not completing, and generally explore what is happening to your machine

Trang 12

introductions to both SYSV and BSD ps output since some systems either combine features of both (for example, AIX) or have both versions (for example, Solaris 2.3, which has SYSV /usr/bin/ps and BSD /usr/ucb/ps)

Introduction to SYSV ps Output

If you are using SYSV, you should read this section to learn about the meaning of the various fields output by ps

Look at what happens when you enter ps:

Now look at what happens when you enter ps -f:

$ ps -f

UID PID PPID C STIME TTY TIME COMD

sartin 1400 1398 80 18:31:32 pts/5 0:01 -sh

Trang 13

sartin 1406 1400 25 18:34:33 pts/5 0:00 ps -f

$

The UID field tells which user ID owns the process Your login name should appear here The PPID field tells the process identifier of the parent of the process; notice that the PPID of ps -f is the same as the PID of -sh The C field is process-utilization information used by the scheduler The STIME is the time the process started

Next, look at what happens when you enter ps -l:

On some SYSV systems with real-time scheduling additions, you may see output such as the following if you enter ps -c:

On some SYSV systems running the Fair Share Scheduler, you may see output such as the following if you enter ps -f:

Trang 14

$ ps -f

UID FSID PID PPID C STIME TTY TIME COMMAND

sartin rddiver 18735 18734 1 Mar 12 ttys0 0:01 -ksh

sartin rddiver 19021 18735 1 18:47:37 ttys0 0:01 xdivesim

sartin rddiver 19037 18735 4 18:52:58 ttys0 0:00 ps -f

root default 18734 136 0 Mar 12 ttys0 0:01 rlogind

NOTE: The BSD ps command predates standard UNIX option processing It does

not take hyphens to introduce options On systems where one ps acts like either SYSV or BSD (e.g., AIX ps), the absence of the hyphen is what makes it run in BSD mode

Trang 15

Look at what happens when you enter ps l:

$ ps l

F UID PID PPID CP PRI NI SZ RSS WCHAN STAT TT TIME COMMAND

20408020 343 22711 22631 0 25 0 48 0 TW c0 0:00 rlogin brat

8000 343 22712 22711 0 1 0 48 0 socket TW c0 0:00 rlogin brat

20000001 343 23122 22631 19 29 0 200 400 R c0 0:00 ps l

$

The F field gives a series of flags that tell you about the current state of the process Check your system manuals for information on interpreting this field The UID field tells the user ID that owns the process Your login name should appear here The PPID field tells the process identifier of the parent of the process; notice that the PPID of the second rlogin is the same as the PID of the other, its parent process The CP is process utilization information used by the scheduler The PRI field is the priority of the process; a lower number means more priority to the scheduler See the section "Prioritizing Processes" for more information on the scheduler The SZ field shows the process size The RSS field shows the resident set size, which is the actual amount of computer memory occupied by the process The WCHAN field tells what event, if any, the process is waiting for

Interpretation of the WCHAN field is specific to your system

Look at what happens when you enter ps u:

Trang 16

23126 c0 R 0:00 0 0 0 200 420 xx 0.0 1.6 ps

$

The SL field tells how long the process has been sleeping, waiting for an event to occur The RE field tells how long the process has been resident in memory The PAGEIN field tells the number of disk input operations caused by the process, to read in pages that were not already resident in memory The LIM field tells the soft limit on memory used

Checking on Your Processes with ps

This section gives a few handy ways to examine the states of certain processes you might care about Short examples are given using the SYSV and BSD versions of ps

Everything You Own

Viewing all processes that you own can be useful in looking for jobs that you

accidentally left running or to see everything you are doing so you can control it On

SYSV, you type ps -u userid to see everything owned by a particular user Try ps -u

$LOGNAME to see everything you own:

20000001 343 861 835 25 31 0 204 440 R p0 0:00 ps l

20088001 343 857 856 0 3 0 32 344 Heapbase S p1 0:00 -ksh HOME=/t

$

Specific Processes

Trang 17

Looking at the current status of a particular process can be useful to track the progress (or

lack thereof) of a single command you have running On SYSV you type ps -pPID to

see a specific process:

$

Specific Process Groups

Looking at the status of a process group (See the section "Job Control and Process

Groups.") can be useful in tracking a particular job you run On SYSV you can use ps

-gPGID to see a particular process group:

$ ps -lg19080

F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME COMD

1 S 343 19080 19057 0 158 24 710340 51 39f040 ttys3 0:58 fin_analysis

1 S 343 19100 19080 0 168 24 71f2c0 87 7ffe6000 ttys3 2:16 fin_marketval

Trang 18

UID PID PPID C STIME TTY TIME COMMAND

root 19056 136 0 19:21:00 ttys3 0:00 rlogind

sartin 19080 19057 0 19:23:53 ttys3 1:01 fin_analysis

sartin 19057 19056 0 19:21:01 ttys3 0:00 -ksh

sartin 19100 19080 0 19:33:53 ttys3 3:43 fin_marketval

sartin 19082 19057 0 19:23:58 ttys3 0:00 vi 19unxor.adj

Trang 19

$

Specific User

Looking at processes run by a particular user can be useful for the system administrator

to track what is being run by others and to deal with "runaway" processes On SYSV

enter ps -u userid to see everything owned by a particular user:

$ ps -fusartin

UID PID PPID C STIME TTY TIME COMMAND

sartin 18743 18735 0 Mar 12 ttys0 0:31 collect_stats

sartin 19065 19057 1 19:21:04 ttys3 0:00 vi 19unxor.adj

sartin 19057 19056 0 19:21:01 ttys3 0:00 -ksh

sartin 18735 18734 0 Mar 12 ttys0 0:00 -ksh

sartin 19066 18743 8 19:21:12 ttys0 0:00 ps -fusartin

$

On BSD, there is no simple, standard way to see processes owned by a particular user other than yourself

Checking on a Process with time

The time command prints out the real, system, and user time spent by a command (in ksh, the built-in time command will time a pipeline as well) The real time is the amount of clock time it took from starting the command until it completed This will include time spent waiting for input, output, or other events The user time is the amount of CPU time used by the code of the process The system time is the amount of time the UNIX kernel spent doing things for the process The time command prints real, user, and sys times on separate lines (BSD time may print them all on one line) Both csh and ksh have built-in versions of time that have slightly different output formats The csh built-in time

command prints user time, system time, clock time, percent usage, and some I/O statistics all on one line The ksh time built-in time command prints real, user, and sys time on separate lines, but uses a slightly different format for the times than does time:

Trang 20

Background and Foreground Processes

So far, you have seen examples and descriptions of a user typing a command, watching

as it executes, possibly interacting during its execution, and eventually completing This

is the default way your interactive shell executes processes Using only this order of events means your shell executes a single process at a time This single process is running

in the foreground Shells are able to keep track of more than one process at a time In this type of environment, one process at most can be in the foreground; all the other processes are running in the backgound This allows you to do multiple things at once from a single screen or window You can think of the foreground and the background as two separate places where your interactive shell keeps processes The foreground holds a single

process, and you may interact with this process The background holds many processes, but you cannot interact with these processes

Foreground Processing

Running a process in the foreground is very common—it is the default way your shell executes a process If you want to write a letter using the vi editor, you enter the

command vi letter and type away After you enter the vi command, your shell starts the vi

process in the foreground so you can write your letter In order for you to enter

information interactively, your process must be in the foreground When you exit the editor, you are terminating the process After your foreground process terminates, but not before, the shell prompts you for the next command

This mode of execution is necessary for all processes that need your interactions It would be impossible for the computer to write the letter you want without your input Mind reading is not currently a means of input, so you commonly type, use your mouse, and even sometimes speak the words But not all processes need your input—they are designed to be able to get all the necessary input via other ways They may be designed to get input from the computer system, from other processes, or from the file system Still, such processes may be designed to give you information Status information could

be reported periodically, and usually the process results are displayed at a certain point If

Trang 21

you wish to see this information as it is reported, the process must be running in the foreground

Where Is the Background and Why Should You Go There?

Sometimes a program you run doesn't need you to enter any information or view any results If this is the case, there is no reason you need to wait for it to complete before doing something else UNIX shells provide a way for you to execute more than one process at a time from a single terminal The way you do this is to run one or more

processes in the background The background is where your shell keeps all processes other than the one you are interacting with (your foreground process) You cannot give input to a process via standard input while it is in the background—you can give input via standard input only to a process in the foreground

The most common reason to put a process in the background is to allow you to do

something else interactively without waiting for the process to complete For example, you may need to run a calculation program that goes through a very large database, computing a complicated financial analysis of your data and then printing a report; this may take several minutes (or hours) You don't need to input any data because your database has all the necessary information You don't need to see the report on your screen since it is so big you would rather have it saved in a file and/or printed on your laser printer So when you execute this program, you specify that the input should come from your database (redirection of standard input) and the report should be sent to a file (redirection of standard output) At the end of the command you add the special

background symbol, & This symbol tells your shell to execute the given command in the background Refer to the following example scenario

$ fin_analysis < fin_database > fin_report &

Trang 22

(all your calculations are complete), your shell may print a termination message on your screen, followed by a prompt

Job Control

Some shells (C shell, csh, and Korn shell, ksh, are two) have increased ability to

manipulate multiple processes from a single interactive shell Although graphical

interfaces have since added the ability to use multiple windows (each with it's own

interactive shell) from one display, job control still provides a useful function

First you need to understand the shell's concept of a job A job is an executed command line Recall the discussion of processes created during execution of a command For many command lines (for example, pipelines of several commands), several processes are created in order to carry out the execution The whole collection of processes that are created to carry out this command line belong to the same process group By grouping the processes together into an identifiable unit, the shell allows you to perform operations on the entire job, giving you job control

Job control allows you to do the following:

 Move processes back and forth between the foreground and background

 Suspend and resume process execution

Each job or process group has a controlling terminal This is the terminal (or window) from which you executed the command Your terminal can only have one foreground process (group) at a time A shell that implements job control will move processes

between the foreground and the background

The details of job control use are covered in the section "Job Control and Process

Groups."

Signaling Processes

When a process is executing, UNIX provides a way to send a limited set of messages to this process: It sends a signal UNIX defines a set of signals, each of which has a special meaning Then the user, or other processes that are also executing, can send a specific signal to a process This process may ignore some signals, and it may pay attention to others As a nonprogramming user, you should know about the following subset of

signals The first group is important for processes, no matter what shell you are using The second group applies if your shell supports job control

General Process Control Signals

HUP Detection of terminal hangup or controlling process death

Trang 23

INT Interactive attention signal—INTR control character generates this

KILL Termination—process cannot ignore or block this

QUIT Interactive termination—QUIT control character generates this

TERM Termination—process may ignore or block this

Job Control Process Control Signals

CONT Continue a stopped process—process cannot ignore or block this

STOP Stop a process—process cannot ignore or block this

TSTP Interactive stop—SUSP control character generates this

TTIN Background job attempted a read—process group is suspended

TTOU Background job attempted a write—process group is suspended

The default action for all the general process control signals is abnormal process

termination A process can choose to ignore all signals except the KILL signal There is

no way for you to tell what processes are ignoring what signals But if you need to

terminate a process, the KILL signal cannot be ignored and can be used as a last resort when attempting to terminate a process

The default action for the job control process control signals is suspending process

execution, except for the CONT signal which defaults to resuming process execution Once again, a process may choose to ignore most of these signals The CONT signal cannot be ignored, so you can always continue a suspended process The STOP signal will always suspend a process because it cannot be ignored

Except for KILL and STOP, a process may catch a signal This means that it can accept the signal and do something other than the default action For example, a process may choose to catch a TERM signal, do some special processing, and finally either terminate

or continue as it wishes Catching a signal allows the process to decide which action to take If the process does not catch a signal and is not ignoring the signal, the default action results

Killing Processes

At some time or other, you will run a command and subsequently find out that you need

to terminate it You may have entered the wrong command, you may have entered the right command but at the wrong time, or you may be stuck in a program and can't figure out how to exit

If you want to terminate your foreground process, the quickest thing to try is your

interrupt control character This is usually set to Ctrl+C, but make sure by looking at your stty -a output The interrupt control character sends an INT signal to the process It is possible for a program to ignore the INT signal, so this does not always terminate the

Trang 24

process A second alternative is to use your quit character (often Ctrl +\, set using stty

quit char), which will send a QUIT signal A process can ignore the QUIT signal If your

shell supports job control (C or Korn shells), you can suspend the process and then use the kill command Once again, your process can ignore the suspend request If you don't have job control or if none of these attempts work, you need to find another window, terminal, or screen where you can access your computer From this other shell you can use the ps command along with the kill command to terminate the process To terminate a process that is executing in the background, you can use the shell that is in the foreground

on your terminal

The kill Command

The kill command is not as nasty as it sounds It is the way that you can send a signal to

an executing process (see the section "Signaling a Process") A common use of the kill command is to terminate a process, but it can also be used to suspend or continue a

Finding What to Kill Using ps

To send a signal to a process via the kill command, you need to somehow identify the particular process Two commands can help you with this: the ps command and the jobs command All UNIX systems support some version of the ps command, but the jobs command is found in job control shells only (See the section "Job Control and Process Groups" for details on job control and the jobs command.)

The ps command shows system process information for your computer The processes listed can be owned by you or other users, depending on the options you specify on the ps command Normally, if you want to terminate a process, you are the owner It is possible for the superuser (root) to terminate any processes, but non-root users may only terminate their own processes This helps secure a system from mistakes as well as from abuse Terminating a process can be a three-step process: first you should check the list of processes with ps See the section "Monitoring Processes" if you're not sure how to do this The output of ps should contain the process identifier of each process Make sure you look for the PID column and not the PPID column The PPID is the process ID for the parent process Terminating the parent process could cause many other processes to terminate as well

Second, you can send a signal to the process via the kill command The kill command takes the PID as one argument; this identifies which process you want to terminate The

Trang 25

kill command also takes an optional argument, which is the signal you wish to send The default signal (if you do not specify one) is the TERM signal There are several signals that all attempt to terminate a process Whichever one you choose, you may specify it by its name (for example, TERM) or by a number The name is preferable because the signal names are standardized The numbers may vary from system to system To terminate a process with PID 2345, you might try kill -HUP 2345 This sends the HUP signal to process 2345

Third, you should check the process list to see if the process terminated Remember that processes can ignore most signals If you specified a signal that the process ignored, the process will continue to execute If this happens, try again with a different signal

TIP: If you have a CPU-intensive job running in the background and you want

to get some work done without killing the job, try using kill -STOP PID This will force

the job to be suspended, freeing up CPU time for your more immediate tasks When you

are ready for the job to run again, try kill -CONT PID

Determining Which Signal to Send

The sure way to make a process terminate is to send it the KILL signal So why not just send this signal and be done with it? Well, the KILL signal is important as a last resort, but it is not a very clean way to cause process termination A process cannot ignore or catch the KILL signal, so it has no chance to terminate gracefully If a process is allowed

to catch the incoming signal, it has an opportunity to do some cleaning up or other

processing prior to termination

Try starting with the TERM signal If your interrupt control character did not work, the INT signal probably won't either, but it is probably a reasonable thing to try next anyway

A common signal that many processes catch and then cleanly terminate is the HUP signal, so trying HUP next is a good idea If you would like a core image of the process (for use with a debugging tool), the QUIT signal causes this to happen If your process isn't exiting at this point, it might be nice to have the core image for the application

developer to do debugging If none of these signals caused the process to terminate, you can fall back on the KILL signal; the process cannot catch or ignore this signal

NOTE: If your process is hung up waiting for certain events (such as a network file

server that is not responding), not even kill will have any visible effect immediately As long as your process isn't using CPU time, you can probably stop worrying about it The hung process will abort if the event ever occurs (for example, the file server responds or

Trang 26

the request times out), but it might not go away until the next time you reboot

If you need a list of the available signals, the -l option to the kill command will display this list You can also check the kill and signalf man pages for descriptions of each signal The signals described in this section are the standard signals, but some systems may have additional supported signals Always check the manual for your system to be sure

The dokill Script An Example

Look at the dokill script as an example of how to kill a process reasonably and reliably:

#!/bin/sh

# TERM, HUP and INT could possibly come in a different order

# TERM is first because it is what kill does by default

# INT is next since it is a typical way to let users quit a program

# HUP is next since many programs will make a recovery file

# QUIT is next since it can be caught and often generates a core dump

# KILL is the last resort since it can't be caught, blocked or ignored for sig in TERM INT HUP QUIT KILL

Trang 27

# Here we sleep if we tried to kill anything

# This gives the process(es) a chance to gracefully exit

# before dokill escalates to the next signal

Logging Out with Background Processes

After you start using executing processes in the background, you may forget or lose track

of what processes you have running You can always check on your processes by using the ps command (see the section "Monitoring Processes") Occasionally, you will try to exit from your shell when you have processes running in the background By default, UNIX tries to terminate any background or stopped jobs you have when you log out UNIX does this by sending a HUP signal to all of your child processes

NOTE: As a safeguard, job control shells (such as csh and ksh) issue a warning

instead of allowing you to log out The message will be similar to "You have stopped (running) jobs." If you immediately enter exit again, the shell will allow you to log out without warning But, beware! The background processes are terminated immediately If you don't want these background processes to be terminated, you must wait until they have completed before exiting There is no way to log out while keeping the processes alive unless you plan ahead

Using nohup

Trang 28

Some of the commands you use may take so long to complete that you may not be able to (or want to) stay logged in until they complete To change this behavior, you can use the nohup command The word nohup simply precedes your normal command on the

command line Using nohup runs the command, ignoring certain signals This allows you

to log out, leaving the process running As you log out, all your existing processes (those processes with your terminal as the controlling terminal) are sent the HUP signal Since the process on which nohup is used ignores this signal, you can log out and the process will not terminate If you have a nohup process in the background as you attempt to log out, your shell may warn you on your first exit command and require an immediate second exit in order to actually log out (If yours is a shell that does job control, such as ksh or csh, see the section "Job Control and Process Groups.")

NOTE: There are several varieties of the nohup command The SYSV nohup

executable arranges for the command to ignore NOHUP and QUIT signals but does nothing regarding the TERM signal If the output is going to standard out, it is redirected

to the file nohup.out (or alternately to $HOME/nohup.out if you can't write to the first)

The C shell has a built-in nohup command It arranges for the command to ignore TERM signals (In C shell, background commands automatically ignore the HUP signal.) It does not redirect output to the file nohup.out

Your system or shell may have a slight variation on the exact signals ignored and whether the nice value is changed when you use nohup

Prioritizing Processes

Part of administering your processes is controlling how much CPU time they use and how important each process is relative to the others UNIX supplies some fairly simple ways to monitor and control CPU usage of your process This section describes how to use UNIX nice values to control your process CPU usage By setting nice values for large jobs that aren't time critical, you can make your system more usable for other jobs that need to be done now

What Is a Priority?

The UNIX kernel manages the scheduling of all processes on the system in an attempt to share the limited CPU resource fairly Because UNIX has grown as a general purpose time-sharing system, the mechanism the scheduler uses tries to favor interactive

processes over long-running, CPU-intensive processes so that users perceive good system response UNIX always schedules the process that is ready to run (not waiting for I/O or

an event) with the lowest numerical priority (that is, lower numbers are more important)

If two processes with the same priority are ready, the scheduler will schedule the process

Trang 29

that has been waiting the longest If your process is CPU intensive, the kernel will

automatically change your process priority based on how much CPU time your process is using This gives preference to interactive applications that don't use lots of CPU time

NOTE: Low PRI means high priority You may find it a bit confusing that lower

numbers for priority mean "higher" priority Try thinking of the scheduler starting out at priority zero and seeing if any processes at that priority are ready If not, the scheduler tries priority 1, and so on

To see how the UNIX scheduler works, look at the example in Table 19.1 In this

example, three processes are each running long computations, and no other processes are trying to run Each of the three processes will execute for a time slice and then let one of the other processes execute Note that each process gets an equal share of the CPU If you run an interactive process, such as a ps, while these three processes are running, you will get priority to run

Table 19.1 Scheduling three CPU-intensive processes

Running Waiting Waiting

Waiting Running Waiting

Waiting Waiting Running

Running Waiting Waiting

Waiting Running Waiting

Waiting Waiting Running

Trang 30

the nice value in calculating the priority Once again, if you run an interactive process, like a ps, while these three processes are running, you will get priority to run

Table 19.2 Scheduling three CPU-intensive processes, one nicely

Running Waiting Waiting

Waiting Running Waiting

Waiting Waiting Running

Running Waiting Waiting

Waiting Running Waiting

Running Waiting Waiting

Waiting Waiting Running

Waiting Running Waiting

Running Waiting Waiting

Waiting Running Waiting

Using renice on a Running Process

BSD introduced the ability to change the nice value of other processes that are owned by you The renice command gives you access to this capability If you run a job and then decide it should be running with lower priority, you can use renice to do that

CAUTION: Not all systems have the renice command Most systems based on

BSD have it Some systems, which are not based on BSD have added renice The renice command on your system may take slightly different arguments than in the examples here Check your system documentation to see if you have renice and what arguments it takes

On BSD-based systems, the renice command takes arguments in this manner:

renice priority [ [-p] pid ] [ -g pgrp ] [ -u userid ]

The priority is the new nice value desired for the processes to be changed The -p option (the default) allows a list of process identifiers; you should get these from ps or by saving the PID of each background task you start The -g option allows a list of process groups;

if you are using a shell that does job control you should get this from the PID of each

Ngày đăng: 07/08/2014, 02:23