Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top