I am trying to create a task which runs in the background (doesn't block the terminal) which i can then terminate via a terminal command.
For this i have created a task with multiprocessing and saving the pid of the process in a seperate file. Also setting the deamon to True so it runs even if the main programm exits
What happens:
- daemon = False:
The process blocks the terminal, however i can terminate it on another terminal successfully - daemon = True:
The main programm exists imidiatly (which makes sense), however the terminate command returns a error:
An error occurred while terminating process: [WinError 87] The parameter is incorrect
PID_FILE = os.path.join(tempfile.gettempdir(), "monsieur_oracle.pid")
def infinite_task():
with open(PID_FILE, "w") as f:
f.write(str(os.getpid()))
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
print("Background task terminated.") # Never printed in the terminal(makes sense)
@app.command(name="t-start")
def start():
loop_process = multiprocessing.Process(target=infinite_task)
loop_process.daemon = True # Keep the process running independently
loop_process.start()
time.sleep(4)
print(f"Application started with process PID {loop_process.pid}. Press Ctrl+C to terminate.")
return
@app.command(name="t-stop")
def terminate():
if os.path.exists(PID_FILE):
with open(PID_FILE, "r") as f:
pid = int(f.read())
try:
os.kill(pid, signal.SIGTERM)
print(f"Sent termination signal to process with PID {pid}")
except ProcessLookupError:
print(f"No process found with PID {pid}. It may have already terminated.")
except PermissionError:
print(f"Permission denied while trying to terminate the process with PID {pid}.")
except Exception as e:
print(f"An error occurred while terminating process: {str(e)}")