LoginSignup
1
3

More than 3 years have passed since last update.

子プロセスを含めたkill

Last updated at Posted at 2020-11-22

概要

子プロセスを含め、killをするためのツールです。python用です。
(pythonのプロセスで縛りを掛けています。)
検証はlinuxのみしてあります。

使い方は、
そのまま実行すると、子プロセスを持つ親プロセスの一覧が表示されるので、
(例としてproc_01.py proc_02.pyの子プロセスを持つプログラムが実行中とします。)

$ python terminate_children_process.py

python 関連の子プロセスを持つprocess一覧
コマンドラインにPIDを指定すると、子プロセスを含めてterminate します。
{'pid': 26727, 'cmdline': ['python', 'proc_01.py']}
{'pid': 26747, 'cmdline': ['python', 'proc_02.py']}

終了させたいpidを指定し再び実行します。

$ python terminate_children_process.py 26747

terminate 子プロセス 26849
terminate 子プロセス 26850
terminate 子プロセス 26851
terminate  親プロセス 26747

ソース(terminate_children_process.py)

#terminate_children_process.py
import sys
import psutil

if len(sys.argv)==1:
    #python 関連の子プロセスを持つprocessの表示
    print("python 関連の子プロセスを持つprocess一覧")
    print("コマンドラインにPIDを指定すると、子プロセスを含めてterminate します。")

    PROCNAME = "python"
    for proc in psutil.process_iter([ "pid"  ,  'cmdline'  ]):
        if proc.name()[:len(PROCNAME)] == PROCNAME:
            p = psutil.Process(proc.pid)
            if len(p.children()) >0:
                print(proc.info)

else:
    #指定したPIDとその子プロセスを含めてterminate

    target_pid=int(sys.argv[1])
    p = psutil.Process(target_pid)

    #子のterminate
    pid_list=[pc.pid for pc in p.children(recursive=True)] 
    for pid in pid_list:
        psutil.Process(pid).terminate ()
        print("terminate 子プロセス {}" .format(pid))

    #親のterminate
    p.terminate ()
    print("terminate  親プロセス {}" .format(target_pid))

参考

psutil documentation

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3