Java Reference
In-Depth Information
ject has a waitFor() method that lets you do so, and an exitValue() method that tells you
the “return code” from the process. Finally, should you wish to forcibly terminate the other
process, you can do so with the Process object's destroy() method, which takes no argu-
ment and returns no value. Example 24-5 is ExecDemoWait , a program that runs whatever
program you name on the command line (along with arguments), captures the program's
standard output, and waits for the program to terminate.
Example 24-5. ExecDemoWait.java
// A Runtime object has methods for dealing with the OS
Runtime r = Runtime . getRuntime ();
Process p ;
// Process tracks one external native process
BufferedReader is ;
// reader for output of process
String line ;
// Our argv[0] contains the program to run; remaining elements
// of argv contain args for the target program. This is just
// what is needed for the String[] form of exec.
p = r . exec ( argv );
System . out . println ( "In Main after exec" );
// getInputStream gives an Input stream connected to
// the process p's standard output. Just use it to make
// a BufferedReader to readLine() what the program writes out.
is = new
new BufferedReader ( new
new InputStreamReader ( p . getInputStream ()));
while
while (( line = is . readLine ()) != null
null )
System . out . println ( line );
System . out . println ( "In Main after EOF" );
System . out . flush ();
try
try {
p . waitFor ();
// wait for process to complete
} catch
catch ( InterruptedException e ) {
System . err . println ( e );
// "Can'tHappen"
return
return ;
}
System . err . println ( "Process done, exit status was " + p . exitValue ());
See Also
You wouldn't normally use any form of exec() to run one Java program from another in this
way; instead, you'd probably create it as a thread within the same process, because this is
Search WWH ::




Custom Search