Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill a process based on PID in Java

I have this so far:

public static void main(String[] args) {

    try {
        String line;
        Process p = Runtime.getRuntime().exec(
                System.getenv("windir") + "\\system32\\" + "tasklist.exe");

        BufferedReader input = new BufferedReader(new InputStreamReader(
                p.getInputStream()));

        while ((line = input.readLine()) != null) {
            System.out.println(line); // <-- Parse data here.
        }
        input.close();
    } catch (Exception err) {
        err.printStackTrace();
    }

    Scanner killer = new Scanner(System.in);

    int tokill;

    System.out.println("Enter PID to be killed: ");

    tokill = killer.nextInt();

}

}

I want to be able to kill a process based on the PID a user enters. How can I do this? (Only needs to work on Windows). *NB: Must be able to kill any process, inc. SYSTEM processes, so I'm guessing a -F flag will be needed if using taskkill.exe to do this?

So if I had

Runtime.getRuntime().exec("taskkill /F /PID 827");

how can I replace "827" with my tokill variable?

like image 562
user1221937 Avatar asked Mar 05 '12 20:03

user1221937


People also ask

How do you kill a process with changing PID?

You can use ps to find the PID of the process, then pass that to kill : kill $(ps -C /usr/lib/gvfs/gvfsd-mtp -o pid=) The -C flag specifies a command name to search for in the list of processes, and the -o pid= option means ps will print only the PID. The result is passed as the only argument to kill .

How do you kill a process in java?

If you start the process from with in your Java application (ex. by calling Runtime. exec() or ProcessBuilder. start() ) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.

How do I kill a specific process in Windows java?

So by using the java process name you are now able to kill the desired process. This command will execute the “jps -m” command and get the PID of the java processes which contain the given “JAVA_PROCESS_NAME” and execute a “taskkill /F /PID” over. N.B.1: replace the “JAVA_PROCESS_NAME” by your own process name.


1 Answers

Simply build the string to kill the process:

String cmd = "taskkill /F /PID " + tokill;
Runtime.getRuntime().exec(cmd);
like image 123
Martijn Courteaux Avatar answered Nov 10 '22 22:11

Martijn Courteaux