How is it possible to get p.exitcode=None right after p.terminate()?

Viewed 331

The following code, sometimes returns as error that python can't compare None with an integer.

This means that p.exitcode is None even after p.terminate(). However in the docs is stated that

This (the exitcode) will be None if the process has not yet terminated.

How is this possible?

The code:

for j in range(3):
    p = multiprocessing.Process(target = functions_that_hangs, args = (arguments,))
    p.start()
    p.join(180)

    if p.is_alive: # used to check if process is still runing
        p.terminate()

    if p.exitcode >= 0 : # used to check if process completed successfully 
        break
1 Answers

terminate() doesn't literally terminate the process:

On POSIX OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess() is called to stop the child.

Both these operations are asynchronous: they request the process to terminate, but don't wait for actual termination.

To wait for actual termination (which guarantees availability of exitcode), use wait():

if p.is_alive:
    p.terminate()
    p.wait()

wait() returns the exit code, and since Python 3.3 it takes a timeout argument, so you can shorten your code to:

for j in range(3):
    p = multiprocessing.Process(...)
    p.start()
    exitcode = p.wait(180)
    if exitcode >= 0:
        break
Related