2013-01-15 56 views

回答

6

如果你知道下面的代碼過程中使用的PID殺從Java應用程序:

Runtime.getRuntime().exec("taskkill /F /PID <process_id>"); 

地方,就是你的進程id/F用來強制殺。注意,這隻適用於使用Windows的情況。

從這裏你可以擴展這個工作來動態獲取進程ID和殺死而不是硬編碼。

使用系統屬性os.name您可以獲取os的名稱並相應地更改命令。

+1

'kill -9 '也適用於一些* nix口味。 – Chris

+0

謝謝@Chris。 :) –

2

除了上面的帖子,你可以過濾掉PID與此代碼(鴕鳥政策知道,如果它可以工作更簡單)

此代碼列表中的所有進程,並可以過濾掉一些特定一個,如果你想要

package runtime; 

import java.util.Scanner; 

public class Process_Check { 

public static void main(String[] args) throws Exception { 
     Processes.ALL_PROCESSES.listProcesses(); 
    } 
public static enum Processes implements IProcessListingStrategy { 
     ALL_PROCESSES; 

     private IProcessListingStrategy processListing = selectProcessListingStrategy(); 

     public void listProcesses() throws Exception { 
      processListing.listProcesses(); 
     } 

     private IProcessListingStrategy selectProcessListingStrategy() { 
      //todo add support for mac ... 
      return isWindows() ? new WinProcessListingStrategy() : new LinuxProcessListingStrategy(); 
     } 

     private static boolean isWindows() { 
      return System.getProperty("os.name").toLowerCase().indexOf("win") >= 0; 

     } 
    } 

    static interface IProcessListingStrategy { 
     void listProcesses() throws Exception; 
    } 

    static abstract class AbstractNativeProcessListingStrategy implements IProcessListingStrategy { 
     public void listProcesses() throws Exception { 
      Process process = makeProcessListingProcessBuilder().start(); 
      Scanner scanner = new Scanner(process.getInputStream()); 
      while (scanner.hasNextLine()) { 
       System.out.println(scanner.nextLine()); 
      } 
      scanner.close(); 
      process.waitFor(); 
     } 

     protected abstract ProcessBuilder makeProcessListingProcessBuilder(); 
    } 
    static class WinProcessListingStrategy extends AbstractNativeProcessListingStrategy { 
     @Override 
     protected ProcessBuilder makeProcessListingProcessBuilder() { 
      return new ProcessBuilder("cmd", "/c", "tasklist"); 
     } 
    } 

    static class LinuxProcessListingStrategy extends AbstractNativeProcessListingStrategy { 
     @Override 
     protected ProcessBuilder makeProcessListingProcessBuilder() { 
      return new ProcessBuilder("ps", "-e"); 
     } 
    } 
} 
相關問題