【问题标题】:How to get the PID of running application in Windows?如何获取 Windows 中正在运行的应用程序的 PID?
【发布时间】:2014-02-06 11:20:38
【问题描述】:

这里有我的代码 sn-p:

 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 中做到这一点?

【问题讨论】:

    标签: java windows pid


    【解决方案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

    【讨论】:

      【解决方案2】:

      这个问题已经回答了herehere

      基本上,没有简单的方法可以完成任务,除非您使用JNI 库或反射,如链接问题中所建议的那样。

      【讨论】:

      • 谢谢! @alberto。我能够获得主进程的PID,但它仍然无法杀死主进程的子进程。我仍在尝试寻找一个好的解决方案或解决方法。
      猜你喜欢
      • 2018-03-21
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      相关资源
      最近更新 更多