Version 5.1 by Pascal Robert on 2010/09/13 00:23

Hide last authors
smmccraw 1.1 1 Here, the "cat" and "outputCat" are debugging output categories:
2
Quinton Dolan 3.1 3 {{code}}
smmccraw 1.1 4
Quinton Dolan 3.1 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 }
smmccraw 1.1 29
Quinton Dolan 3.1 30 {{/code}}
smmccraw 1.1 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
Pascal Robert 4.1 36 === Mike Schrag ===
smmccraw 1.1 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]].