Skip to content

Latest commit

 

History

History
63 lines (49 loc) · 8.2 KB

如何kill一个进程组或会话.org

File metadata and controls

63 lines (49 loc) · 8.2 KB

如何kill整一个进程组或会话

http://morningcoffee.io/killing-a-process-and-all-of-its-descendants.html 看到的,记录一下

今天才知道,kill 命令可以后接一个负数来表示发送信号给一个进程组中的所有进程。

Negative PID  values  may  be used  to  choose  whole  process groups; see the PGID column in ps command output.  
A PID of -1 is special; it indicates all processes except the kill process itself and init.

所以我们可以用 kill -SIGTERM -- -$PGID 来强制关闭指定进程组中的所有进程。

kill 命令的这个特性是由 kill(2) 系统调用而来的。

DESCRIPTION
       The kill() system call can be used to send any signal to any process group or process.

       If pid is positive, then signal sig is sent to the process with the ID specified by pid.

       If pid equals 0, then sig is sent to every process in the process group of the calling process.

       If  pid  equals  -1,  then  sig is sent to every process for which the calling process has permission to send signals, except for
       process 1 (init), but see below.

       If pid is less than -1, then sig is sent to every process in the process group whose ID is -pid.

kill(2) 系统调用并不支持直接根据Session ID来发送信号(甚至对于某些UNIX实现来说都没有Session ID这个概念),因此要发送信号给某个 Session 中的进程需要遍历 /proc/ 中的进程树( /proc/pid/stat ),搜集符合 SID 的进程,然后发送信号给这些进程。

pkill 命令已经帮我们实现了这一功能,只需要执行 pkill -s $SID 就可以了。

最后,要察看进程组ID 和 SessionID,可以通过 ps 的 j 参数看到

ps j -A

其中 PGID 即为进程组ID, SID 为 SessionID