首页 > 代码库 > 快速理解孤儿进程和僵尸进程
快速理解孤儿进程和僵尸进程
下面是我大约11年前在读APUE(《Unix环境高级编程》)对孤儿进程和僵尸进程的理解,为了便于记忆,采用打比方的方式予以解释。 (当然不一定精准,后面我会贴出wikipedia上的专业解释。)
- 操作系统OS好比一个公司,公司的CEO就是init进程。
- 任何一个子进程都有父进程,就好比任何一个人都有爹。 这里假定子进程为小明,父进程为小明的爸爸。
- init进程作为OS公司的CEO,是小明的爷爷(注:小明的爸爸很可能是CEO的第N代后人,N>=1,这里假定N=1)。
- 任何一个进程在退出之后都会进入僵尸状态,它占有的资源需要交还给操作系统(也就是公司)。
- 小明的爷爷跟小明的爸爸有个约定,你的儿子你负责,除非你不在了。
- 父进程在子进程退出之前退出了,也就是小明还活着,忽然没有爸爸了,于是就成了孤儿(orphan)进程。按照约定,小明(子进程)被小明的爷爷(init进程)收养。
- 子进程退出的时候父进程还在,也就是小明没了,小明的爸爸还健在。但是子进程进入僵死状态,父进程什么也不管(没有调用wait等待子进程退出)。敢情小明不是小明爸爸亲生的吧,接下来没多久,父进程也退出了,也就是小明的爸爸也挂了。于是子进程(小明)变成了僵尸(zombie)进程。 按照小明爷爷与小明爸爸之间的约定,既然爹都不管,那爷爷也不管,爱谁谁。
附: 维基百科对对孤儿进程和僵尸进程的解释
1. Orphan process
In a Unix-like operating system any orphaned process will be immediately adopted by the special init system process: the kernel sets the parent to init. This operation is called re-parenting and occurs automatically. Even though technically the process has the "init" process as its parent, it is still called an orphan process since the process that originally created it no longer exists.
【译文】在类Unix操作系统中,任何一个丧父的进程都会被一个名字为init的特殊系统进程所领养:操作系统内核会将已丧父的进程的父亲设置为init进程。这一操作被称之为re-parenting,而且自动执行。虽然从技术上讲,丧父的进程有一个父亲(也就是init进程),但是它还是被称为孤儿进程,因为最开始创建它的父进程已经不在了。
2. Zombie process
On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution (via the exit system call) but still has an entry in the process table: it is a process in the "Terminated state". This occurs for child processes, where the entry is still needed to allow the parent process to read its child‘s exit status: once the exit status is read via the wait system call, the zombie‘s entry is removed from the process table and it is said to be "reaped". A child process always first becomes a zombie before being removed from the resource table. In most cases, under normal system operation zombies are immediately waited on by their parent and then reaped by the system – processes that stay zombies for a long time are generally an error and cause a resource leak.
The term zombie process derives from the common definition of zombie — an undead person. In the term‘s metaphor, the child process has "died" but has not yet been "reaped". Also, unlike normal processes, the kill command has no effect on a zombie process.
Zombie processes should not be confused with orphan processes: an orphan process is a process that is still executing, but whose parent has died. These do not remain as zombie processes; instead, (like all orphaned processes) they are adopted by init (process ID 1), which waits on its children. The result is that a process that is both a zombie and an orphan will be reaped automatically.
【译文】在Unix和类Unix操作中,一个僵尸进程(zombie或defunct)是一个已经结束运行的进程(通过exit系统调用),但是该进程在进程表中还占有一个进程表项: 处于终止状态。
快速理解孤儿进程和僵尸进程