Process

Posted it芮菜鸟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Process相关的知识,希望对你有一定的参考价值。

Modern operating systems are usually multitasking,meaning that they create the illusion(错觉)of doing more than one thing at once by rapidly switching from one executing program to another.The Linux kernel manages this through the use of processes.Processes are how Linux organizes the different programs waiting for their turn at the CPU.

Sometimes a computer will become sluggish(呆滞的,迟钝的) or an application will stop responding.In this chapter,we will look at some of the tools available at the command line that let us examine what programs are doing,and how to terminate processes that are misbehaving.

This chapter will introduce the following commands:

ps - Report a snapshot(快照) of current processes

top- Display tasks

jobs - List active jobs

bg - Place a job in the background

fg - Place a job in the foreground

kill - Send a signal to a process

killall - Kill processes by name

shutdown - Shutdown or reboot the system

 

How does process work

When a system starts up,the kernel initiates a few of its own activities as processes and launches a program called init.init,in turn,(依次地) runs a series of shell scripts(located in /etc) called init scripts,which start all the system services.Many of these services are implemented as daemon(守护神) programs,programs that just sit in the background and do their thing without having any user interface.So even if we are not logged in,the system is at least a little busy performing routine stuff.

The fact that a program can launch other programs is expressed in the process scheme as a parent process producing a child process.

The kernel maintains information about each process to help keep things organized.For example,each process is assigned a number called a process ID or PID.PIDs are assigned in ascending(上升的,向上的)order,with init always getting PID 1. The kernel also keeps track of memory assigned to each process,as well as the processes\' readiness execution.(以及程序准备恢复执行)。Like files,processes also have owners and user IDs,effective user IDs,etc.

 

View process(查看进程)

The most commonly used command to view processes(there are several) is ps.The ps program has a lot of options,but in it simplest form it is used like this:

The result in this example lists three processes,process 3649 ,process 3655 and process 5403,which are su,bash and ps respectively(各自地,分别地).As we can see, by default,ps doesn\'t show us very much,just the processes associated with the current terminal session.To see more,(为了看到更多信息,)we need to add some options,but before we do that,let\'s look at the other fields produced by ps.TTY is short for "Teletype,"and refers to the controlling terminal for the process.Unix is showing its age here.The TIME field is the amount of CPU time consumed by the process.As we can see,neither process makes the computer work very hard.

If we add an option,we can get a bigger picture of what the system is doing:

Adding the "x" option(note that there is no leading dash) tells ps to show all of our processes regardless of what terminal(if any) they are controlled by.The presence of a "?" in the TTY column(列,专栏) indicates no controlling terminal.Using this option,we see a list of every process that we own.

Since the system is running a lot of processes,ps produces a long list.It is often helpful to pipe the output from ps into less for easier viewing.Some option combinations also produce long lines of output,so maximizing the terminal emulator window may be a good idea,too.

A new column tiltled STAT has been added to the output.STAT is short for "state" and reveals the current status of the process:

Table 11-1:Process States

State Meaning
R Running.This means that the process is running or ready to run.
S Sleeping.A process is not running;rather,it is waiting for an event,such as keystroke or network packet.
D Uninterruptible(不可中断) Sleep.Process is waiting for I/O such as a disk drive.
T Stopped.Process has been instructed to stop.More on this later
Z A defunct(死进程) or "zombie" process.This is a child process that has terminated,
< A high priority process.It\'s possible to grant more importance to a process,giving it more time on the CPU.This property(属性) of a process is called niceness.A process with high priority is said to be less nice because it\'s taking more of the CPU\'s time,which leaves less for everybody else.
N A low priority process.A process with low priority(a "nice" process) will only get processor time after oter processes with higher priority have been servied.

The process state may be followed by other characters.These indicate various exotic (由外国引进的,非本地的) process characteristics.See the ps man page for more detail.

Another popular set of option is "aux"(without a leading dash.)This gives us even more information:

This set of options displays the processes belonging to every user.Using the options without the leading dash invokes(调用) the command with "BSD style"behavior.The Linux version of ps can emulate the behavior of the ps program found in several different Unix implementations.With these options,we get these additional columns:

Table 11-2:BSD Style ps Column Headers

Header Meaning
USER User ID.This is the owner of the process.
%CPU CPU usage in percent
%MEN Memory usage in percent
VSZ Virtual memory size
RSS Resident Set Size.(驻留集大小)The amount of physical memory(RAM)the process is using in kilobyte 
START Time when the process started.For values over twenty four hours,a date is used.

View the process dynamically with the top command(用top命令动态查看进程)

While the ps command can reveal a lot about what the machine is doing,it provides only a snapshot(快照) of the machine\'s state at the moment the ps command is executed.To see a more dynamic view of the machine\'s activity,we use the top command:

The top program displays a continuously updating(by default,every 3 seconds)display of the system processes listed in order of process activity.The name "top" comes from the fact that the top program is used to see the "top" processes on the system.The top display consists of two parts:a system summary at the top of the display,followed by  a table of processes sorted by CPU activity:

 top进程显示按进程活动顺序列出的系统进程的连续更新(默认情况下,每3秒更新一次)。top这个名字来源于,top这个名字是用来观察系统中的顶端进程的。top显示结果由两部分组成:上面是进程概要,下面是进程列表以CPU的使用率排序。

 

The system summary contains a lot of good stuff.Here\'s a rundown(裁减,纲要):(其中系统概要包含许多有用信息。下表是对系统概要的说明:)

Table 11-3:top Information Fields

Row Field Meaning
1 top Name of the program
  14:59:20 the current time(可以注意一下,这里的时间会每3s更新一次)
  up 6:30 This is called uptime.(正常运行时间) It is the amount of time since the machine was last booted.In this example,the system has been up for six and a half hours.
  2 users There are two users logged in 
  load average: Load average(加载平均值) refers to the number of processes that are waiting to run,that is,the number of processes that are in a  runnable state and are sharing the CPU.Three values are shown,each for a different period(时期,时代,句号,句点,这里指时期吧) of time.The first is the average for the last 60 seconds,the next the previous 5 minutes,and finally the previous 15 minutes.Values under 1.0 indicate that the machine is not busy.
 2 Tasks:  This summarizes the number of processes and their various process states. 
 3 CPu(s):  This row describes the character of the activities that the CPU is performing. 
   0.7%us 0.7% of the CPU is being used for user processes.This means processes outside of the kernel itself. 这意味着进程在内核之外
   1.0%sy 1.0%of the CPU is being used for system(kernel) processes. 1.0%的CPU时间被用于系统(内核)进程
   0.0%ni 0.0%of the CPU is being used by "nice"(low priority) processes. 0.0%的CPU时间被用于“nice”(低优先级)进程
   98.3%id 98.3%  of the CPU is idle(空闲的)
   0.0%wa 0.0%of the CPU is waiting for I/O 
 4 Mem:  Shows how physical RAM is bing used 
 5 Swap:  Shows how swap space(virtual memory) is being used. 展示交换分区(虚拟内存)的使用情况。

The top program accepts a number of keyboard commands.The two most interesting are h,which displays the program\'s help screen,and q,which quits top.

Both major desktop environments provide graphical applications that display information similar to top(in much the same way that Task Manager in Windows works 和windows中的任务处理器差别不多),but I find that top is better than the graphical versions because it is faster and it consumes(消耗) far fewer system resources.After all,our system monitor(监测) program shouldn\'t be the source of the system slowdown that we are trying to track.

 

Control process

Now that we can see and monitor processes,let\'s gain some control over them.For our experiments,we\'re going to use a little program called xlogo as our guinea pig.(豚鼠,实验对象)The xlogo program is a sample program supplied with the X Window System(the underlying(根本的) engine that makes the graphics on our display go)which simply displays a resizable(大小可调的) window containing the X logo.First,we\'ll get to know our test subject(主题):

After entering the command,a small window containing the logo should appear somewhere on the screen.On some systems,xlogo may print a warning message,but it may be safely ignored.

Tip:If your system does not include the xlogo program,try using gedit or kwrite instead.(rhel7.0只有gedit有用)

We can verify(核实,查证) that xlogo is running by resizing its window.(通过调整它的窗口大小,我们能够证明xlogo程序正在运行)If the logo is redrawn in the new size,the program is running.

Notice how our shell prompt has not returned?This is because the shell is waiting for the program to finish,just like all the other programs we have used so far.If we close the xlogo window,the prompt returns.

 

Interrupt a process(中断一个进程)

Let\'s observe what happens when we run xlogo again.First,enter the xlogo command and verify(核实,查证) that the program is running.Next,return to the terminal window and type Ctrl-c.

In a terminal,typing Ctrl-c,interrupts a program.This means that we politely asked the program to terminate.After typing Ctrl-c,the xlogo window closed and the shell prompt returned.

Many(but not all) command line programs can be interrupted by using this technique.

 

Put a process in the background(execution)

Let\'s say we wanted to get the shell prompt back without terminating the xlogo program.We\'ll do this by placing the program in the background.Think of the terminal as having a foreground(with stuff visible on the surface like the shell prompt) and a background (with hidden stuff behind the surface.) To launch a program so that it is imediately placed in the background,we follow the command with an- "&" character:

After entering the command,the xlogo window appeared and the shell prompt returned,but some funny numbers were printed too.This message is part of a shell feature called job control.With this message,the shell is telling us that we have started job number1("[1]") and that it has PID 28236.If we run ps,we can see our process:

The shell\'s job control facility also gives us a way to list the jobs that are have been launched from our terminal.Using the jobs command,we  can see this list:

The results show that we have one job,numbered "1",that it is running,and that the command was xlogo &.

 

 Return a process to the foreground.(进程返回到前台)

A process in the background is immune(免疫的) from keyboard input,including any attempt(试图,尝试) interrupt it with a Ctrl-c.To return a process to the foreground,use the fg command,this way:

The command fg followed by a percent sign and job number(called a jobspec) does the trick.If we only have one background job,the jobspec is optional.To terminate xlogo,type Ctrl -c.

Stop a process(停止一个进程)

Sometimes we\'ll want to stop a process without terminating it.(厉害了,学到了,停止和终止不一样。)This is often done to allow a foreground process to be moved to the background.To stop a foreground process,type Ctrl-z.Let\'s try it.At the command prompt,type xlogo,the Enter key,then Ctrl-z:

After stopping xlogo,we can verify that the program has stopped by attempting to resize the xlogo window.We will see that it appears quite dead.We can either restore the program to the foreground,using the fg command,or move the program to the background with the bg command:

As with the fg command,the jobspec is optional if there is only one job.

Moving a process from the foreground to the background is handy if we launch a graphical program from the command,but forget to place it in the background by appending the trailing"&".

Why would you want to launch a graphical program from the command line?There are two reasons.First,the program you wish to run might not be listed on the window manager\'s menus(such as xlogo).Secondly,by launching a program from the command line,you might be able to see error messages that would otherwise be invisible(看不见的,暗藏的)if the program were launched graphically.Sometimes,a program will fail to start up when launched from the graphical menu.By launching it from the command line instead,we may see an error message that will reveal the problem.Also,some graphical programs have many interesting and useful command line options.

 

Signals

The kill command is used to "kill" programs.This allows us to terminate programs that need killing.Here\'s an example:

We first launch xlogo in the background.The shell prints the jobspec and the PID of the background process.Next,we use the kill command and specify the PID of the process we want to terminate.We could have also specified the process using a jobspec(for example,"%1")instead of a PID.

While this is all very straightforward(正直的,坦率的,老实的,简单的,易懂的),there is more to it than that.(但不仅仅这些)The kill command doesn\'t exactly "kill" programs,rather it sends them signals.Signals are one of several ways that the operating system communicates with programs.We have already seen signals in action with the use of Ctrl-c and Ctrl-z.When the terminal receives one of these keystrokes(按键),it sends a signal to the program in the foreground(前端运行的程序).In the case of Ctrl-c,a signal called INT(Interrupt) is sent;with Ctrl-z,a signal called TSTP(Terminal Stop.)Programs,in turn,"listen" for signals and may act upon them as they are received.The fact that a program can listen and act upon signals allows a program to do things like save work in progress when it is sent a termination signal.

 

Send a signal to the process through the Kill Command(通过kill命令给进程发送信号)

The kill command is used to send signals to programs.Its most comman syntax looks like this:

If no signal is specified on the command line,then the TERM(Terminate) signal is sent by default.The kill command is most often used to send the following signals:

Table 11-4:Common Signals

Number Name Meaning
1 HUP  Hangup.(挂断)This is a vestige(遗迹) of the good old days when terminals were attached to remote computers with phone lines and modems(这是美好往昔的痕迹,那时候终端机通过电话线和调制解调器连接到无端的计算机).The signal is used to indicate to programs that the controlling terminal has "hung up."The effect of this signal can be demonstrated (de加强+monstr显示+ate表动词>>加强显示>>证明)by closing a terminal session.The foreground program running on the terminal will be sent the signal and will terminate.This signal is also used by many daemon(守护神) programs to cause a reinitialization(重新初始化)(许多守护进程也使用这个信号,来重新初始化).This means that when a daemon is sent this signal,it will restart and re-read its configuration file.The Apache web server is an example of a daemon that uses the HUP signal in this way.
2 INT   Interrupt.Performs the same function as the Ctrl-c key sent from the terminal.It will usually terminate a program.
9 KILL  kill.This signal is special.Whereas(但是,而) programs may choose to handle signals sent to them in different ways,including ignoring them all together,the KILL signal is never actually sent to the target program.Rather,the kernel immediately terminates the process.When a process is terminated in this manner,it is given no opportunity to "clean up"after itself or save its work.For this reason,the KILL signal should only be used as a last resort when other termination signals fail.
15 TERM  Terminate.This is the default signal sent by the kill command.If a program is still "alive" enough to receive signals,it will terminate 
18 CONT Continue.This will restore a process after a STOP signal.
19  STOP  Stop.This signal causes a process to pause without terminating.Like the KILL signal,it is not sent to the target process,and thus it cannot be ignored. 

 Let\'s try out the kill command:

In this example,we start the xlogo program in the background and then send it a HUP signal with kill.The xlogo program terminates and the shell indicates that the background process has received a hangup signal.You may need to press the enter key a couple of times before you see the message.Note that signals may be specified either by number or by name,including the name prefixed(加...作为前缀) with the letters "SIG"(搞不懂它为毛要加SIG就为了强调发送的信号是用名字表示的?):

 

Repeat the example above and try out the other signals.Remember,you can also use jobspecs(百分号+工作序号) in place of PIDs.

Processes,like files,have owners,and you must be the owner of a process (or the superuser) in order to send it signals with kill,there are other signals frequently(频繁地) used by the system.Here is a list of other common signals:

Table 11-5:Other Comman Signals

Number Name Meaning
3 QUIT quit
11 SEGV Segmentation(分割,here 段) Violation(违反,冒犯,侵害,违反,强奸)(段错误).This signal is sent if a program makes illegal use of memory,that is ,it tried to write somewhere it was not allowed to.
20 TSTP Terminal Stop.This is the signal sent by the terminal when the Ctrl-z key is pressed.Unlike the STOP signal,the TSTP signal is received by the process and may be ignored.
28 WINCH Window Change.This is a signal sent by the system when a window changes size.Some programs,like top and less will respond to this signal by redrawing(重拉伸,再拉拔) themselves to fit the new dimensions(尺寸).

For the curious,a complete list of signals can be seen with the following command:

 

Send signals to multiple processes via killall command(通过killall命令给多个进程发送信号)

It\'s also possible to send signals to multiple processes matching a specified program or user name by using the killall command.Here is the syntax:

To demonstrate(说明),we will start a couple of instances of the xlogo program and then terminate them:

 

More process related commands(更多和进程相关的命令)

Since monitoring processes is an important system administration task,there are a lot of commands for it.there are a lot of commands for it.Here are some to play with:

Table 11-6:Other Process Related Commands

Command Description
pstree Output a process list arranged in a tree-like pattern showing the parent/child relationships between processes.
vmstat Outputs a snapshot(快照) of system resource usage including,memory,swap and disk I/O.To see a continuous display,follow the command with a time delay(in seconds) for updates.For example:vmstat5.Terminate the output with Ctrl-c.
xload A graphical program that draws a graph showing system load over time
tload Similar to the xload program,but draws the graph in the terminal.Terminate the output with Ctrl-c.

以上是关于Process的主要内容,如果未能解决你的问题,请参考以下文章

Process使用

打开web浏览器

根据process杀死进程

process

java命令执行漏洞

Java代码启动/关闭进程