[Python] How to Properly Stop a GNU screen Session and Ensure All Running Processes Are Killed?

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

    I’m using GNU screen to run a service, but when I stop the session, the processes running inside it are not always terminated properly. This results in ports remaining occupied and prevents the service from restarting cleanly.

    I have a Python class that manages screen sessions, where I start a service using:

    screen -dmS my_service -L -Logfile /tmp/my_service.log zsh -i


    To stop the session, I currently do:

    screen -S my_service -X stuff 'kill -TERM -$$\n'
    screen -X -S my_service quit

    The Problem:

    • The screen session is closed, but the processes inside it (like a java spring app ./gradlew bootRun) continue running.
    • This leads to ports being occupied, making it impossible to restart the service without manually killing the lingering processes.
    What I Want:


    I need a reliable way to stop a screen session and ensure all processes inside it are properly terminated.

    I tried to get the session’s PID and kill all its processes before quitting the session:

    import subprocess

    def stop_screen_session(session_name: str):
    """Stop a screen session and ensure all processes inside are killed."""
    try:
    # Get the session's main PID
    get_pid_cmd = f"screen -ls | grep {session_name} | awk '{{print $1}}' | cut -d'.' -f1"
    result = subprocess.run(get_pid_cmd, shell=True, capture_output=True, text=True, check=False)
    pid = result.stdout.strip()

    if pid:
    # Kill all processes in the session's process group
    subprocess.run(f"pkill -TERM -g {pid}", shell=True, check=True)

    # Check if any processes are still running and force kill if necessary
    check_cmd = f"ps -eo pgid | grep {pid}"
    result = subprocess.run(check_cmd, shell=True, capture_output=True, text=True, check=False)

    if result.stdout.strip():
    print(f"Processes still running under session {session_name}, forcing termination.")
    subprocess.run(f"pkill -KILL -g {pid}", shell=True, check=True)

    # Quit the screen session
    subprocess.run(f"screen -X -S {session_name} quit", shell=True, check=True)

    print(f"Screen session {session_name} stopped successfully.")

    except subprocess.CalledProcessError as err:
    print(f"Failed to stop session {session_name}: {err}")

    stop_screen_session("my_service")


    This is not working properly ..

    Continue reading...

Compartilhe esta Página