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?

2 Answers 2

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

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.

1
  • 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 7, 2014 at 2:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.