exit and clean up python fork

2.7k Views Asked by At

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

here it's the 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)
1

There are 1 best solutions below

5
On BEST 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.