天天看点

僵死进程和孤儿进程

在unix高级系统编程一书中:

在说明f o r k函数时,一定是一个父进程生成一个子进程。上面又说明了子进程将其终止状

态返回给父进程。但是如果父进程在子进程之前终止,则将如何呢?其回答是对于其父进程已

经终止的所有进程,它们的父进程都改变为i n i t进程。我们称这些进程由i n i t进程领养。其操作

过程大致是:在一个进程终止时,内核逐个检查所有活动进程,以判断它是否是正要终止的进

程的子进程,如果是,则该进程的父进程I D就更改为1 ( i n i t进程的I D )。这种处理方法保证了每

个进程有一个父进程。

在U N I X术语中,一个已经终止、但是其父进程尚未

对其进行善后处理(获取终止子进程的有关信息、释放它仍占用的资源)的进程被称为僵死

进程( z o m b i e)。p s ( 1 )命令将僵死进程的状态打印为Z。如果编写一个长期运行的程序,它

f o r k了很多子进程,那么除非父进程等待取得子进程的终止状态,否则这些子进程就会变成僵

死进程。

一个父进程已终止的进程称为孤儿进程(orphan process),这种进程由i n i t进程收养。

之前觉得僵尸进程和孤儿进程关系不大,最近看了深入理解linux内核一书才明白其实关系比较大。

when a process terminates, the kernal changes the appropriate process descriptor pointers of all the existing chrildren of the terminated process to make them become children of init. This process monitors the execution of all it's children and routinely issues wait4() system calls, whose side effect is to get rid of all orphaned zombies.

这段是书中第一章关于僵死进程的介绍,中文版把side effect翻译成副作用,让我费解了一阵,感觉翻译成另一个作用更合适些。书中还有更详细的介绍。

下面是进程的状态的一个叙述

PROCESS STATE CODES

Here are the different values that the s, stat and state output specifiers (header "STAT" or "S") will display to describe the state of a process:(ps -elf可以看到s列,ps aux可以看到stat列)

D uninterruptible sleep (usually IO)

R running or runnable (on run queue)

S interruptible sleep (waiting for an event to complete)

T stopped, either by a job control signal or because it is being traced

W paging (not valid since the 2.6.xx kernel)

X dead (should never be seen)

Z defunct ("zombie") process, terminated but not reaped by its parent

For BSD formats and when the stat keyword is used, additional characters may be displayed:

< high-priority (not nice to other users)

N low-priority (nice to other users)

L has pages locked into memory (for real-time and custom IO)

s is a session leader