danielnovais92
danielnovais92

Reputation: 633

Waiting for process to end in Java

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

Upvotes: 2

Views: 10804

Answers (2)

Renjith
Renjith

Reputation: 3274

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.

Upvotes: 3

Chris McCabe
Chris McCabe

Reputation: 1030

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.

Upvotes: 5

Related Questions