Ned Hulton
Ned Hulton

Reputation: 678

Python Multiprocessing. Check if process is running

How can I print "process timed out and terminated" if that happens after ten seconds?

How can I print "process completed successfully" if no termination happens?

import multiprocessing
import time

def hello():
    #process to be terminated after ten seconds

if __name__ == '__main__':
    proc = multiprocessing.Process(target=hello)
    proc.start()
    time.sleep(10)
    proc.terminate()

Upvotes: 1

Views: 3573

Answers (2)

tdelaney
tdelaney

Reputation: 77407

Instead of sleeping, "join" the process with a timeout. If the process exits in less than 10 seconds, you'll get the notification right away. Otherwise, after 10 seconds you can check the exit code. I added a third case of a non-zero exit code for a general failure to this example.

import multiprocessing
import time

def hello():
    #process to be terminated after ten seconds

if __name__ == '__main__':
    proc = multiprocessing.Process(target=hello)
    proc.start()
    proc.join(10)
    if proc.exitcode is None:
        proc.terminate()
        proc.join(1)
        if proc.exitcode is None:
            proc.kill()
        print("process timed out and terminated")
    elif proc.exitcode == 0:
        print("process completed successfully")
    else:
        print("unexpected error") 

There is a window where the child exits properly right after the parent decides everything went wrong. If that's a problem, you could do something more complicated.

Upvotes: 1

Ned Hulton
Ned Hulton

Reputation: 678

 import time
 import multiprocessing
    
 def hello():
    #process to be terminated after ten seconds
    
 if __name__ == '__main__':
        proc = multiprocessing.Process(target=hello)
        proc.start()
        time.sleep(5)
        if proc.is_alive():
            print("Job not finished")
        else:
            print("Job done")
        proc.terminate()

Upvotes: 1

Related Questions