#πŸ”’ Invalid Process ID for multiprocess

4 messages Β· Page 1 of 1 (latest)

sullen finch
#

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:

  1. daemon = False:
    The process blocks the terminal, however i can terminate it on another terminal successfully
  2. 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)}")
icy oarBOT
#

@sullen finch

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

icy oarBOT
#

@sullen finch

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.