DEV Community

Rick Dumpleton
Rick Dumpleton

Posted on

Kill Stubborn Processes By Name

import os
import signal

# Function to find processes with a partial name and attempt to kill them
def find_and_kill_processes(partial_name):
    # Use pgrep to find all PIDs with a partial process name match
    pid_list = os.popen(f'pgrep -f "{partial_name}"').read().split()

    # Check if any matching processes were found
    if not pid_list:
        print(f"No processes found matching: {partial_name}")
    else:
        print(f"Processes found matching: {partial_name}")
        for pid in pid_list:
            print(f"PID: {pid}")

        # Ask for confirmation to kill the processes
        confirm = input("Do you want to kill these processes? (y/n): ").strip().lower()
        if confirm == 'y':
            for pid in pid_list:
                try:
                    # First attempt to terminate the process with SIGTERM (less forceful)
                    os.kill(int(pid), signal.SIGTERM)
                    print(f"Terminating process with PID {pid} using SIGTERM")
                except ProcessLookupError:
                    print(f"Process with PID {pid} not found.")
                except PermissionError:
                    print(f"Permission denied to terminate process with PID {pid}. Trying SIGKILL...")
                    try:
                        # If SIGTERM fails, try SIGKILL (more forceful)
                        os.kill(int(pid), signal.SIGKILL)
                        print(f"Forcibly killing process with PID {pid} using SIGKILL")
                    except ProcessLookupError:
                        print(f"Process with PID {pid} not found.")
            print("Processes terminated.")
        else:
            print("Operation canceled.")

# Get user input for the partial process name
partial_name = input("Enter a partial process name to find and kill: ").strip()

# Call the function to find and potentially kill matching processes
find_and_kill_processes(partial_name)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)