본문 바로가기

Programing/Python

Python subprocess Popen에서 좀비프로세스 방지 (zombie-processes 방지)


python 배치안에서 Popen로 새로운 프로세스를 병렬적으로 실행하는데 부모 process가 멈춰있고 자식 프로세스들이 defunct되어 있는 것을 확인했다. 


예를 들면 아래의 ls 실행 같이 말이다. 
 subprocess.call( ('ps', '-l') )
process.wait()
print "after wait"
subprocess
.call( ('ps', '-l') )

Example output:

$ python so2760652.py
F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
0 S   501 21328 21326  0  80   0 -  1574 wait   pts/2    00:00:00 bash
0 S   501 21516 21328  0  80   0 -  1434 wait   pts/2    00:00:00 python
0 Z   501 21517 21516  0  80   0 -     0 exit   pts/2    00:00:00 ls <defunct>
0 R   501 21518 21516  0  80   0 -   608 -      pts/2    00:00:00 ps


해결책을 찾아 봤는데 아래에서 보면 나랑 비슷한 증상을 이야기 한다. 
http://www.agapow.net/programming/python/subprocess-zombies 


The problem is to do with IO buffers. (See herehere and here.)  The system I/O fills up stdout and stderr with the output from the program and waits for it to be consumed (i.e. read) before it goes any further. And so the process hangs.

child process에서 IO 버퍼가 차버리면 이걸 소비하기 전에 process가 hang될 수 있다는 것이다. 

해서 현재 subprocess로 실행되는 스크립트들의 stdout과 stderr를 모두 /dev/null로 던져 놓고 한번 지켜보려고 한다. 

참고로 내가 쓰던 python 버전은 Python 2.6.5 이다.