Stefan Witzel
Stefan Witzel

Reputation: 343

Forking and exiting from child in python

I'm trying to fork a process, do something in the child and then exit from it (see code below). To exit I first tried sys.exit which turned out to be a problem because an intermediate function caught the SystemExit exception (as in the code below) and so the child didn't actually terminate. I figured out that I should use os._exit instead. Now the child terminates, but I still see defunct processes lying around (when I do ps -ef). Is there a way to avoid these?

import os, sys

def fctn():
    if os.fork() != 0:
        return 0
#   sys.exit(0)
    os._exit(0)

while True:
    str = raw_input()
    try:
        print(fctn())
    except SystemExit:
        print('Caught SystemExit.')

Edit: this was actually not really a Python question but more of a Unix question (so I guess results may vary depending on the system). Ivan's answer suggests that I should do something like

def handleSIGCHLD(sig, frame):
    os.wait()

signal.signal(signal.SIGCHLD, handleSIGCHLD)

while for me a simple

signal.signal(signal.SIGCHLD, signal.SIG_IGN)

also works.

And then it's probably true that I should use some library...

Upvotes: 0

Views: 1931

Answers (2)

neotrinity
neotrinity

Reputation: 230

you are better off using the subprocess module for your need. Its the preferred way of forking off a process.

https://docs.python.org/2/library/subprocess.html#subprocess.check_call

Upvotes: 0

ivan_pozdeev
ivan_pozdeev

Reputation: 36106

You should wait() for a child to remove its zombie process entry from the table.

Finally, to offload tasks to children, you may be better off with multiprocessing.

Upvotes: 4

Related Questions