Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute code just before terminating the process in python?

This question concerns multiprocessing in python. I want to execute some code when I terminate the process, to be more specific just before it will be terminated. I'm looking for a solution which works as atexit.register for the python program.

I have a method worker which looks:

def worker():
    while True:
        print('work')
        time.sleep(2)
    return

I run it by:

proc = multiprocessing.Process(target=worker, args=())
proc.start()

My goal is to execute some extra code just before terminating it, which I do by:

proc.terminate()
like image 633
trojek Avatar asked Mar 17 '26 05:03

trojek


1 Answers

Use signal handling and intercept SIGTERM:

import multiprocessing
import time
import sys
from signal import signal, SIGTERM

def before_exit(*args):
    print('Hello')
    sys.exit(0)  # don't forget to exit!


def worker():
    signal(SIGTERM, before_exit)
    time.sleep(10)

proc = multiprocessing.Process(target=worker, args=())
proc.start()
time.sleep(3)
proc.terminate()

Produces the desirable output just before subprocess termination.

like image 154
leovp Avatar answered Mar 21 '26 10:03

leovp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!