Waiting for process to end in Java
Solution 1
the waitFor() method will make the calling thread to wait until the process p completes(It can be dangerous,since the if the process gets blocked in any infinite loop, the main thread will wait all the time.
I suggest writing some semaphore file, and set some value in it when your process completes from java file.The main method can waiting on checking the status of semaphore file.
Solution 2
If there's no exception thrown, Java is waiting for the process to end. The process may be ending without completing the task at hand. You may need to read the output from the process and display it to find out what's going wrong.
Have a look at this article about using Runtime.exec(): http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
hopefully it will be of some help to you in debugging the problem.
danielnovais92
Updated on June 04, 2022Comments
-
danielnovais92 almost 2 years
So I have this program
String[] cmd = {"gnome-terminal", "--full-screen", "-e", "./toMatrix"}; Process p = Runtime.getRuntime().exec(cmd); copy(p.getInputStream(), System.out); p.waitFor(); System.out.println("Exit value = " + p.exitValue());
And I want it to run, in another process, the C program toMatrix. But I need it to run in a new terminal window and in full screen mode, so I need to pass those parameters. The problem is that the main process does not wait for the Process p to end. What am I doing wrong?
Regards
-
Anuj Kulkarni over 10 yearsFantastic ! It helped me. StreamGobbler !!
-
Ironluca over 8 yearsAlso helpful is the waitFor with timeout waitFor(5, TimeUnit.SECONDS); with timeout of 5 seconds, if the process end can be reasonably certain