Version 2.1 by smmccraw on 2007/07/08 09:45

Hide last authors
smmccraw 1.1 1 Here, the "cat" and "outputCat" are debugging output categories:
2
3 {{panel}}
4
5 Process process=null;
6 try {
7 process = Runtime.getRuntime().exec(commandLine);
8 OutputStream output = process.getOutputStream();
9 output.write(inputString.getBytes());
10 output.close();
11 process.waitFor();
12 DataInputStream dis=new DataInputStream(process.getInputStream());
13 String output;
14 do {
15 output = dis.readLine();
16 if (output !=_null)
17 ________________outputCat.debug(output);
18 ________}_while_(output_!= null);
19 dis.close();
20 } catch (IOException e) {
21 cat.error("IOException: " + e.toString());
22 } catch (InterruptedException e) {
23 cat.error("Interrupted process: " + e.toString());
24 } finally {
25 if (process != null)
26 process.destroy();
27 outputCat.debug("Process finished.");
28 }
29
30 {{/panel}}
31
32 Note: A number of people have reported problems with process.waitFor() on Windows. The WebObjects Development List at Omnigroup has a number of people's workaround code for this problem.
33
34 **Note 2:** The procedure given here, of course, is to call anything executable from the command line from your Java program, not just Perl scripts.
35
36 === Mike Schrag ===
37
38 process.waitFor() is not just a problem on Windows. This code //will// cause problems. Process maintains buffers for stdout and stderr. If you do not consume those streams, you will run into deadlocks. The proper way to use Runtime.exec is to setup a thread for stderr and a thread for stdout and consume them yourself into your own buffer that does not have the same restrictions that the stock VM has.
39
40 There's a good example of this technique on [[JavaWorld>>http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]].
41
42 Category:WebObjects