Manali Kagathara
Manali Kagathara

Reputation: 761

python multiprocessing after kill process give is_alive() status True

I have gone through the python(3.7) documentation to understand the concept of multiprocessing. For Process object there are two methods terminate() and kill. Terminating a process is done using the SIGTERM, and killing the process uses the SIGKILL signal on Unix.

When we terminate the process and check is_alive() status of the process it gives False. but, when I use kill and check the status for the process it gives is_alive() status True. I don't know why it's giving True after killing the process if it is the same as the terminate process.

def test():
    print("in test method")
    time.sleep(3)


if __name__ == '__main__':
    p1 = Process(target=test)
    p1.start()  # start process

    # kill process after 1 sec
    time.sleep(1)
    p1.kill()
    print(p1.is_alive())  # why process alive status true when kill process
    time.sleep(3)
    print(p1.is_alive())

Upvotes: 1

Views: 2724

Answers (2)

Booboo
Booboo

Reputation: 44313

Whether you use kill or terminate, these methods only start the termination of the process. You must then wait for the process to fully terminate by using join (if you try to use sleep, you are only guessing as to how long to sleep for the process to be fully terminated):

p1.kill()
p1.join() # wait for p1 to fully complete
print(p1.is_alive()) # prints False

Upvotes: 4

dildeolupbiten
dildeolupbiten

Reputation: 1342

I think the reason of this is that the time between p1.kill() and print(p1.is_alive()) functions is so short. So I think that, the interpreter is trying to print on the screen whether or not the process is still active before this kill command is finished.

For example if you put time.sleep(0.001) between p1.kill() and print(p1.is_alive()) functions, False value will be printed rather than True value.

import time
from multiprocessing import Process


def test():
    print("in test method")
    time.sleep(3)


if __name__ == '__main__':
    p1 = Process(target=test)
    p1.start()  # start process

    # kill process after 1 sec
    time.sleep(1)
    p1.kill()
    time.sleep(0.001)  # Wait for p1.kill() function is finished.
    print(p1.is_alive())  # why process alive status true when kill process
    time.sleep(3)
    print(p1.is_alive())

Upvotes: 1

Related Questions