Running a custom termination of a process in python multiprocessing

21 Views Asked by At

There may be a simple way to do this, but I am relatively new to python. Essentially, I have two functions in different files. One creates a new process to run the other. However, upon user key stroke (enter key) I would like to send a signal to terminate the other process. However, prior to termination, I would want that process to run some sort of save function then terminate, therefore I cannot use multiprocessing's built-in terminate.

Here's the example code from file 1:

import test_global
import msvcrt
import multiprocessing as mp
import time as t

if __name__ == "__main__":
    process = mp.Process(target=test_global.test)
    process.start()
    
    while True:
        #Emergency Stop
        #Detect user key input
        if msvcrt.kbhit():
            #Detect enter key
            if msvcrt.getwche() == '\r':
                #Emergency function stop
                test_global.emergency_stop = True
                print("Emergency Stop Activated")
                print("Clock Stopped")
                break

And the example code from the file "test_global" of the process its running:

import time as t
import datetime as dt

global emergency_stop
emergency_stop = False

def test():
    while True:
        print(f"No input. {dt.datetime.now()}")
        if emergency_stop:
            save()
            print("function stopped")
            break
        t.sleep(1)


def save():
    """
    Do some save things here
    """
    pass

As you can see, I tried to edit test_global's global variable "emergency_stop" in order to do this. I have thought of using pipes and queues, but then the main process will constantly need to send None until the emergency stop is activated. A queue would be possible, but then the process will constantly need to clear it in search of the actual emergency_stop. I could pickle a variable and read said pickle, but this also seems overly complex, and a bit time consuming.

0

There are 0 best solutions below