분석가의 개발 공부/Python

[Python] 좀비 프로세스 죽이기 (How to kill zombie process)

긴기린그림 2023. 3. 6. 18:02

파이썬 코드를 실행하다가 커널을 shutdown하면 가끔 실행 중인 코드는 없지만 메모리는 어디선가 사용되고 있는 때가 있다. 이 때 실행 중인 pid(Process ID)를 확인하여 처리할 수 있다 (pid : 운영체제에서 프로세스를 식별하기 위해 프로세스에 부여하는 번호).

ps -ef | grep python

실행 중인 python 파일을 출력해보면 맨 왼쪽에 사용 중인 유저, pid를 순서대로 출력해준다. 

 

$ python
>>> import psutil 
>>> for process in psutil.process_iter():
    	print(process.name(), "\t"+str(process.pid), "\t"+process.status())

psutil의 process_iter() 모듈로 현재 실행 중인 pid 목록을 확인하고, 각 pid의 실행 상태를 status로 확인할 수 있다. 실행 중인 pid를 kill 하고 싶다면 kill 명령어로 처리할 수 있다.

kill -9 PID
kill -9 1239

 

process status가 zombie인 pid가 좀비 프로세스인데 여기서 메모리를 붙잡고 있기 때문에 해당 pid를 kill 해야 한다. 그런데 좀비 프로세스는 이름처럼 이미 죽어있는 상태이기 때문에 kill 명령어로도 죽지 않는다. 원래는 해당 pid의 ppid, 즉 parent pid가 child pid의 상태를 체크하게 되는데 좀비 프로세스는 이미 exited된 상태로 ppid에서 exit status code를 읽어올 수 없게 된다. 따라서 좀비 프로세스를 kill 하려면 그 pid가 속해있는 ppid를 kill 하는 방식으로 제거할 수 있다. 삭제하기 전에 ppid의 상태를 먼저 확인하고 kill 하도록 주의하자.

 

만약 ppid가 없고 좀비 pid만 있다면? 좀비 pid가 차지하는 메모리가 크지 않다면 그냥 두고, 아니라면 리부팅이 답이다! parent가 없다면 리부팅을 하지 않는 이상 좀비 프로세스는 계속 남아있게 된다.

 

 

 

Reference

https://medium.com/naukri-engineering/creating-troubleshooting-the-zombie-process-in-python-f4d89c46a85a

 

Creating & Troubleshooting the zombie process in Python

Let’s learn about how the zombie processes are created in python, before creating the zombie process through python code, let’s deep dive…

medium.com