How to get the PID of running application in Windows?

不羁的心 提交于 2019-12-12 02:36:06

问题


I have here my code snippet:

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

What I want to do is to get the PID of the process started executing file.exe.

Is there a way to do that in Java?


回答1:


This question was already answered here and here.

Basically, there's no simple way to achieve the task, unless you use the JNI libraries or reflection, as suggested in the linked questions.




回答2:


This works for me perfectly on 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 "";
}

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



来源:https://stackoverflow.com/questions/21601466/how-to-get-the-pid-of-running-application-in-windows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!