0

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?

Alberto Solano
  • 7,972
  • 3
  • 38
  • 61
prix
  • 123
  • 2
  • 13

2 Answers2

1

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

user1449265
  • 357
  • 1
  • 2
  • 11
0

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.

Community
  • 1
  • 1
Alberto Solano
  • 7,972
  • 3
  • 38
  • 61
  • thank you! @alberto. i was able to get the PID of the main process but still it cannot kill the sub process of the main process. I'm still trying to look for a good solution or perhaps a workaround. – prix Feb 07 '14 at 02:55