Mehrdad Dadvand Mehrdad Dadvand - 3 months ago 23
Linux Question

exit and clean up python fork

i am trying to code socket server with fork in python. somehow a new fork will be created when a client connected and this fork process will handle the connection including send / receive
i ran this script on centos and monitor resources with htop / top to see how many fork (task) shown.the
problem is when i kill some fork by using os._exit(0) htop wont be change (naturally it has to be decreased by killing forks) and when i close python script every thing will back to normal ( Ram usage and tasks )
so what i have to do when i use os._exit(0) to kill some fork process it effects on htop in other hand release all resources and do not wait until its own parent killed ?

here its code to create forks

def test(sock):
//handle socket then return
for i in range (1000):
sock,addr=socket.accept()
pid=os.fork()
if pid==0:
test(sock)
os._exit(0)
elif pid !=-1:
os.waitpid(-1, os.WNOHANG)

Answer

The parent process needs to wait for the child in order for the child process' resources to be released. Until then the process still exists in a "zombie" state, and it will still appear in ps and top etc.

You can call one of os.wait(), os.waitpid(), os.wait3(), or os.wait4().

os.wait3() with the os.WNOHANG option might be most useful to you as it will wait for any child process and the parent will not block until a child terminates (or it's state changes - wait will return child processes that have been stopped or restarted too).

More details on the underlying system calls can be found in the Linux man page: man 2 wait.