2014-02-06 73 views
0

我這裏有我的代碼片段:如何在Windows中獲取正在運行的應用程序的PID?

ArrayList<String> cmd_exec_installer = new ArrayList<String>(); 
cmd_exec_installer.add("file.exe"); 
Process proc = new ProcessBuilder(cmd_exec_installer).start(); 

我想要做的是讓進程的PID開始執行file.exe

有沒有辦法在Java中做到這一點?

回答

0

此問題已經回答herehere

基本上,除非您使用JNI庫或反射,否則沒有簡單的方法來完成任務,正如鏈接問題中所建議的。

+0

謝謝! @alberto。我能夠獲得主進程的PID,但仍然無法殺死主進程的子進程。我仍然在尋找一個好的解決方案或者解決方法。 – prix

1

這完全適用於我在Windows 7:

//Imports 
import com.sun.jna.*; 
import com.sun.jna.platform.win32.Kernel32; 
import com.sun.jna.platform.win32.WinNT; 


private String getWindowsProcessId(Process proc) 
{ 
    if (proc.getClass().getName().equals("java.lang.Win32Process") 
      || proc.getClass().getName().equals("java.lang.ProcessImpl")) { 
     try { 
      Field f = proc.getClass().getDeclaredField("handle"); 
      f.setAccessible(true); 
      long handl = f.getLong(proc); 
      Kernel32 kernel = Kernel32.INSTANCE; 
      WinNT.HANDLE handle = new WinNT.HANDLE(); 

      handle.setPointer(Pointer.createConstant(handl)); 
      return Integer.toString(kernel.GetProcessId(handle)); 

     } catch (Throwable e) { 
     } 
    } 
    return ""; 
} 

來源:http://cnkmym.blogspot.com/2011/10/how-to-get-process-id-in-windows.html

相關問題