Saturday, December 12, 2009

进程状态

使用kill -9那是相当的powerful呀, 无一不乖乖投降。

其实现实中, 不是全部都可以被kill的。我记得以前在freeBSD下就有进程是kill不了的。今天在看《linux系统管理技术手册》一书也提到。使我对进程的状态引起注意

在ps的手册中有如下状态:
D    Uninterruptible sleep (usually IO)
* 这种状态下, 进程是不处理signal的, 只能由中断唤醒
R    Running or runnable (on run queue)
T    Stopped, either by a job control signal or because it is being traced.
Z    Defunct ("zombie") process, terminated but not reaped by its parent.
S    Interruptible sleep (waiting for an event to complete)

平时的job control使用了STOP和CONT两个信号, 如:

jessinio@jessinio-laptop:/tmp$ python sleep.py
^Z
[1]+  Stopped                 python sleep.py
# 暂停后查看情况:
jessinio@jessinio-laptop:/tmp$ jobs
[1]+  Stopped                 python sleep.py
# 得到PID号:
jessinio@jessinio-laptop:/tmp$ ps auxww|grep sleep.py
jessinio 20100  9.8  0.1   5448  2892 pts/2    T    16:50   0:01 python sleep.py
jessinio 20102  0.0  0.0   3036   788 pts/2    R+   16:50   0:00 grep sleep.py
# 发CONT信号:
jessinio@jessinio-laptop:/tmp$ kill -s CONT 20100
# 后多了一个"&"后台工作方式. 有意思!!
jessinio@jessinio-laptop:/tmp$ jobs
[1]+  Running                 python sleep.py &

这个"&"引起了我的问题: 所谓的backgroup是什么意思?

Linux下, 一切都是文件, backgroup除了session id, group id, parent 外, 无非还有一点: stdin, stdout, stderr.

通过一个简单的例子可以排除shell对自己启动的程序的stdout, stderr没有进行redirect, 例子:
#/usr/bin/env python
import os
import sys

while True:
    print str( os.isatty( sys.stdin.fileno() ) )

在shell下, 使用ctrl+Z 发出Stop信号后, 使用kill -s CONT PID使stop的程序继续运行, 就可以看到: stdout有信息, 但是这时的ctrl-Z无法停止正在行动的脚本.

所谓的后台("&"), 其实是shell这个程序(具体到指bash)的一种概念. 每个interactive shell都会有一张表是记录 jobs in the current session.
shell下的ctrl+Z是bash根据jobs表把发送STOP信号发送到指定进程的.



T与S的区别

S状态的出现, 是表示进程在等待. 这种等待一般是:
0. 等待系统分配CPU时间, 这种sleep状态是系统处理的. 其它程序都无法干涉
1. 调用了system call中会出现, 如IO函数, sleep函数. 这是程序自身调用函数后产生的, 也是其它程序无法干涉的

不存在sleep的信号, 也不存在wake up的信号


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.