[kepler-dev] Running Shell Scripts inside Kepler
Tobin Fricke
tobin at pas.rochester.edu
Wed Apr 6 09:50:12 PDT 2005
On Wed, 6 Apr 2005, Dan Higgins wrote:
> Now here is where I ran into trouble!!! On Linux and the Mac, 'R' is a
> shell script, not a simple executable! And apparently, the Java
> runtime.exec() method WILL NOT START A SUBPROCESS SET UP THIS WAY WITH A
> SHELL SCRIPT!!!
The JavaDoc for the 'Process' class contains the following note:
The Runtime.exec methods may not work well for special processes on
certain native platforms, such as native windowing processes, daemon
processes, Win16/DOS processes on Microsoft Windows, or shell scripts.
The created subprocess does not have its own terminal or console. All
its standard io (i.e. stdin, stdout, stderr) operations will be
redirected to the parent process through three streams
(Process.getOutputStream(), Process.getInputStream(),
Process.getErrorStream()). The parent process uses these streams to feed
input to and get output from the subprocess. Because some native
platforms only provide limited buffer size for standard input and output
streams, failure to promptly write the input stream or read the output
stream of the subprocess may cause the subprocess to block, and even
deadlock.
In my test, executing a shell script worked without problem:
[tobin at robin ~/proving]$ ls
foo.sh RunShellScript.class RunShellScript.java
[tobin at robin ~/proving]$ cat foo.sh
#!/bin/sh
echo Hello, World!
[tobin at robin ~/proving]$ cat RunShellScript.java
/* Tobin Fricke
2005-04-06
*/
class RunShellScript {
public static void main(String args[]) {
try {
Process p = Runtime.getRuntime().exec("./foo.sh");
/* Note that 'input' and 'output' are from the perspective of the
controlling Java class. This 'input stream' refers to the process's
stdout! */
java.io.InputStream o = p.getInputStream();
/* Wait for the process to exit. */
p.waitFor();
/* Collect its output. */
int l = o.available();
byte[] b = new byte[l];
o.read(b, 0, l);
System.out.print(new String(b));
} catch (Exception e) {
System.out.println("Woops! " + e);
}
}
}
[tobin at robin ~/proving]$ javac RunShellScript.java
[tobin at robin ~/proving]$ java RunShellScript
Hello, World!
[tobin at robin ~/proving]$
I'd make sure that the R shell script starts with the proper "#!" magic
cookie & interpreter signture. Also, does anyone know how to simply dump
the 'InputStream' obtained from the process to the Java stdout without
doing the silly byte[] --> String business I did?
Tobin
http://web.pas.rochester.edu/~tobin/
More information about the Kepler-dev
mailing list