3

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()
2
  • 1
    There is no way to do that since process.terminate() asks the operating system to kill with SIGTERM. So no finally handlers etc. will be executed. Commented Mar 2, 2017 at 16:31
  • 1
    You can provide a SIGTERM signal handler. See signal.signal in docs.python.org/3.4/library/signal.html Commented Mar 2, 2017 at 16:35

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that this will not work on Windows

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.