Forums

Forking and killing the child

I wonder how I do kill the child when I fork in the console, I haven't tried in WSGI but I guess it the same problem.

Here is the error:

:::python
Traceback (most recent call last): File "/home/emj/mohahahh.py", line 39, in <module>
exit()
File "/usr/local/lib/python2.7/site.py", line 372, in call
raise SystemExit(code)

Hi Emj, would you mind posting the code that is causing the error?

If you were using os.fork then you would save the return value, which is the forked processes pid, then you could use os.kill(pid, 9) to kill it.

But this might not be exactly what you are doing so if you show us some code I might be able to help out a bit more.

Ah maybe I didn't put it quite in the right words: I was trying to do sys.exit(); from the child, which didn't work.

I guess I can send a "quit" over the pipe and have it killed.. :-)

That one was a bit too obscure for me to know off the top of my head :-) But I did find the answer:

os._exit(n)
Exit the process with status n, without calling cleanup
handlers, flushing stdio buffers, etc.

Availability: Unix, Windows.

Note The standard way to exit is sys.exit(n). _exit()
should normally only be used in the child process after a fork().

Reading a bit more about it I discovered that os._exit actually calls the underlying C function on the process calling it. Whereas sys.exit() is actually doing a raise SystemExit. So one is using the operating system to nuke a process, while the other one is raising an exception. An exception which I imagine is being caught by the parent Python process in this situation.