I wish to create a process using java's runtime: for example. Process proc = Runtime.getRuntime().exec("cmd");
Then, I want to somehow wait for the process until it is in 'ready for input' state, which will verify it has finished all of its work. Anyway on how to do it?
One thing that is possible is echoing "---finished---" and checking if this line was written using the stdin of the process. But I dislike the idea.
Is there any better (more formal) approach to do this?
By the way, I need this effect as I descriobed it. I want to wait before writing new commands to the batch file.
Thank you.
Is there any better (more formal) approach to do this?
No. Java provides no way to determine if another program is waiting for input. Indeed, I don't believe that this is possible to determine this at all (for Linux/UNIX) without digging around in kernel memory. (And that would be a really bad idea ... IMO).
Your best bet is to check the external program's output for some text that indicates that a batch has just finished ... and hope that you don't get a false positive. (Or just queue up the batches without waiting for them to complete, though it sounds like that won't be a solution for you.)
Here are a couple ideas. They hinge on whether or not the program you're running expects to read and write from stdin and stdout.
There's no need to wait for a "ready for input" state once you've launched the process. If you need to send commands, use getOutputStream
and write them. If the other program is still getting itself ready, the data you've written will happily sit in a buffer until the program reads from stdin.
Using ProcessBuilder
will let you easily control arguments and environment. Example direct from JavaDocs:
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();
Then, to read or write:
OutputStream out = p.getOutputStream();
out.write("some useful data".getBytes());
out.flush();
Your question seems like a really complicated way of obtaining the final required result.
First, Java has the capacity to write to arbitrary files. Why not use that capability in a single threaded manner? Calling flush will ensure the write is actually performed...
If you really need concurrency for some reason, use a thread over a process. Then, make the thread do what it needs to do and nothing more. Have the parent thread join()
the child thread. When the child thread is finished, your parent thread will resume.
Finally, calling available()
on the output stream or input stream can tell you have much data Java can read before blocking. This isn't what you want exactly, but can be adapted to work I'm guessing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With