我在这里我的代码片段:
ArrayList<String> cmd_exec_installer = new ArrayList<String>(); cmd_exec_installer.add("file.exe"); Process proc = new ProcessBuilder(cmd_exec_installer).start();
我想要做的是获得开始执行file.exe
的进程的PID。
有没有办法在Java中做到这一点?
这个问题已经在这里和这里回答了 。
基本上,没有简单的方法来完成任务,除非你使用JNI库或反射,如链接的问题所建议的。
这在Windows 7上对我完美的工作:
//Imports import com.sun.jna.*; import com.sun.jna.platform.win32.coreel32; 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); coreel32 kernel = coreel32.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