Search code examples
javaexeshortcutprocessbuilder

Process.waitFor() not waiting for executed shortcuts (.lnk)


In Java I want to execute a .lnk shortcut which it self executes a .exe file.

I run the executable like so:

 String currentDir = new File(game.getGamePath()).getCanonicalPath();

 ProcessBuilder processBuild = new ProcessBuilder(currentDir);
 processBuild.command("cmd", "/c", "start" , currentDir);
 Process = processBuild.start();
     try {
        Process.waitFor();
     } catch (InterruptedException ex) {
        Logger.getLogger(AuroraLauncher.class.getName()).log(Level.SEVERE, null, ex);
     }

I want the waitFor() thread blocking method to wait until the actual executed application (.exe file) terminates before it continues not the shortcut. Is there a way to do this simply or do I have to somehow extract the .exe path from the .lnk? if so how would I do that?


Solution

  • Windows command "start" has an option /wait you must specify to tell him it has to wait for the end of the process. This code run until you close notepad:

        @Test
        public void run() throws IOException {
            String currentDir = new File(System.getProperty("user.home"),"desktop/notepad.lnk").getCanonicalPath();
    
            ProcessBuilder processBuild = new ProcessBuilder(currentDir);
            processBuild.command("cmd", "/c", "start","/wait", currentDir);
            Process p= processBuild.start();
            try {
                p.waitFor();
            } catch (InterruptedException ex) {
    
            }
            System.out.println("process terminated!");
    
        }
    

    Simpler than to parse the lnk file.