Process.terminate() method

Method Name:

terminate

Method Signature:

terminate()

Return Value:

NoneType

Parameters:

Not Applicable

Method Overview:

  • Terminates the process corresponding to the process instance on which it was invoked.
  • In Unix-like operating systems it uses SIGTERM signal to terminate the process.In Windows it uses TerminateProcess().
  • It causes the child processes of the terminated process to become orphaned.
  • After a process is terminated using terminate(), any data passing mechanisms held by the process like Queues, Pipes may become corrupt. 
  • If the process has acquired any synchronization objects this may cause a deadlock to other processes that were waiting on those synchronization objects.

Example:

import multiprocessing as multiproc

import time

 

# Process function

def pfunc(mq):

    for i in range(1,20):

        mq.put("Message%d"%i)

        time.sleep(1)

        print("Child:Populated the Queue with:%d"%i)

 

if __name__ == "__main__":

    # Set the method for process creation

    multiproc.set_start_method('fork')

   

    # Create a Queue

    mq = multiproc.Queue()

    childProc = multiproc.Process(target=pfunc,args=(mq,))

    childProc.start()

    print("Parent:After child process has started")

    time.sleep(2)

 

    # Terminate the child process

    childProc.terminate()

    print("Parent:After terminate() on the child process")

 

    # Join will return immediately as the process has been terminated already

    childProc.join()

    print("Parent:Exit code of the child process on terminate():%d"%childProc.exitcode)

 

    if childProc.is_alive() == True:

        print(mq.get()) # Queue may be corrupt if process had encountered a terminate() call

 

Output:

Parent:After child process has started

Child:Populated the Queue with:1

Parent:After terminate() on the child process

Parent:Exit code of the child process on terminate():-1


Copyright 2024 © pythontic.com