import os
import sys
import signal
import errno
def kill_parent_and_children(parent_pid):
try:
# 親プロセスとその子プロセスのPIDを取得
parent_and_children_pids = [parent_pid] + get_child_processes(parent_pid)
# 親プロセスとその子プロセスを終了させる
for pid_to_terminate in parent_and_children_pids:
if pid_to_terminate is not None:
os.kill(pid_to_terminate, signal.SIGKILL) # プロセスを終了させる
except Exception as e:
print(f"Error terminating processes: {str(e)}")
def get_child_processes(parent_pid):
child_processes = []
try:
# /procディレクトリからプロセス情報を取得
proc_dir = '/proc'
for pid_entry in os.listdir(proc_dir):
pid_path = os.path.join(proc_dir, pid_entry)
if os.path.isdir(pid_path) and pid_entry.isdigit():
# プロセスのステータスを読み取り
with open(os.path.join(pid_path, 'status'), 'r') as status_file:
status_lines = status_file.readlines()
# PPid行から親プロセス番号を取得
for line in status_lines:
if line.startswith('PPid:'):
ppid = int(line.split()[1])
if ppid == parent_pid:
child_processes.append(int(pid_entry))
break
except Exception as e:
print(f"Error getting child processes: {str(e)}")
return child_processes
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python3 xxxx.py <parent_pid>")
sys.exit(1)
parent_pid = int(sys.argv[1])
# 親プロセスとその子プロセスをすべて終了させる
kill_parent_and_children(parent_pid)