Kill a PID based process in Java

I still have this:

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 the PID-based process that the user enters. How can i do this? (You only need to work with Windows). * NB: Must be able to kill any process, incl. SYSTEM, so I assume that the -F flag is needed to use taskkill.exe?

So, if I had

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

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

+4
source share
2 answers

Just create a line to kill the process:

 String cmd = "taskkill /F /PID " + tokill; Runtime.getRuntime().exec(cmd); 
+4
source

I am not sitting in front of a Windows computer right now. But if the tasklist works for you, you can use ProcessBuilder to run the windows Taskkill command . Call taskkill as follows with an instance of ProcessBuilder cmd /c taskkill /pid %pid% (replace% pid% with the actual pid). You do not need an absolute path for both executable files, because c:/windows/system32 is in a variable path.

As Eric said (in a comment on your question), there are many who have had this answer before.

+2
source

Source: https://habr.com/ru/post/1399864/


All Articles