目录html
代码示例支持 |
---|
平台: Centos 6.3 |
Python: 2.7.14 |
Github: https://github.com/baidu/CUP |
pid, ppid是你们比较常见的术语, 表明进程号,父进程号. 但pgid是个什么鬼?python
了解pgid以前, 咱们先复习下:mysql
os.system
或者Popen
家族启动子进程这个场景还有个后续就是:linux
这个就是今天咱们遇到的坑, 怎么处理孙子进程. 你们注意, 不只是Python会遇到这个问题, 其余语言包括 Shell 都同样会遇到这种"孙子"进程怎么进程异常处理的问题.git
本期的坑位解法其实有两种, 第一种比较暴力, 简称穷尽搜索孙子法.github
a. 穷尽搜索孙子法, 代码示例sql
关键点:shell
from cup.res import linux pstatus = linux.Process(pid) for child in pstatus.children(recursive=True): os.kill(child, signal.SIGKILL)
b. 得到该进程的 PGID, 进行 kill 操做编程
b1. 先讲个 shell 操做的作法, 使用ps 获取进程的pgid, 注意不是pidbash
# 以mysqld为例, 注意 pgid 项 ps -e -o uid,pid,gid,pgid,cmd|grep mysql
结果:
注意其中第三列, 该进程和子进程都使用了一样的pgid 9779
9790 0 9779 /bin/sh /usr/bin/mysqld_safe --datadir=/home/maguannan/mysql/mysql/....
10171 501 9779 /home/maguannan/bin/mysqld --basedir=/home/maguannan/mysql/....
经过kill -9 -9779
的方式能够杀死该pgid底下的全部子孙进程
b2. 在讲 Python 里的处理方式
import os import signal from cup.res import linux pstatus = linux.Process(pid) os.killpg(pstatus.getpgid(), signal.SIGKILL)
进程组特性
a. 在*unix 编程中, 进程组(man getpgid
)概念是个很重要但容易被忽略的内容
b. 进程组内的全部成员会收到来自相同的信号
引用 wikipedia 原文:
a process group is used to control the distribution of a signal; when a signal is directed to a process group, the signal is delivered to each process that is a member of the group.
坑位解决