Reputation: 41
I'm building an application that should launch other applications on my windows PC. When the app is started my code should wait until I close that program to continue its execution.
System.out.println("Starting ccleaner...");
Process p = Runtime.getRuntime().exec("C:\\Program Files\\CCleaner\\CCleaner64.exe");
System.out.println("Before wait");
p.waitFor();
//Here it should wait until the subprocess is
// exited/the ccleaner programs exit button is clicked
System.out.println("After wait");
All that happens is that it doesn't wait, it executes right away.
I looked up the waitFor()
method in the documentation and it says:
Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.
And this seems pretty clear to me. However I have looked at other questions regarding this issue on this site and found a couple of solutions that involves reading streams, but as I understand these are mostly when you have your own bat files you want to run. But I have tried these as well but not getting it to work. Funny thing is that my code above is more or less identical to the one offered on tutorialpoints.com.
I've also tried using process.isAlive()
but I can't seem to get that one working either.
Does anyone know what I'm doing wrong here?
Upvotes: 4
Views: 661
Reputation: 361595
waitFor()
does exactly what you expect. Your understanding isn't wrong.
I suspect the program you're running is indeed exiting immediately, causing waitFor()
to return straight away. It may be starting one or more child processes that are doing the real work while the parent process exits.
Upvotes: 1