Re: Better way to do error handling here?
On Mon, 19 Oct 2009, Ian Shef wrote:
ram@zedat.fu-berlin.de (Stefan Ram) wrote in news:error-catching-
20091019222539@ram.dialup.fu-berlin.de:
laredotornado <laredotornado@zipmail.com> writes:
phpProcess = Runtime.getRuntime().exec(phpNormalizerCommand);
from a termianl . Is there some way after first ilne of the code above
that I could trap for this error and stop my program if I detect such
an error?
The javadocs are your friend:
"Starting an operating system process is highly system-dependent. Among the
many things that can go wrong are:
The operating system program file was not found.
Access to the program file was denied.
The working directory does not exist.
In such cases an exception will be thrown. The exact nature of the
exception is system-dependent, but it will always be a subclass of
IOException."
None of those are relevant to this situation.
Here, we know that the script being run exists. But the script specifies
an interpreter which may or may not exist - this is a unix thing which i
think doesn't have an equivalent on windows, but basically, a script can
specify which interpreter should run it on its first line, so you can have
scripts for the shell, perl, python, and PHP all happily coexisting and
being run in the same way. If the specified interpreter doesn't exist, the
script will fail.
I had a quick poke at this on OS X, and what happens in the case of a bad
interpreter is that you get no output on either stream, and an exit code
of 255. If you run the command with "bash -c /path/to/file", then you get
the "bad interpreter" message on the error stream, and an exit status of
126.
You could try something like:
Process proc = Runtime.getRuntime().exec("/path/to/script");
Thread.sleep(100); // long enough for the
try {
int exit = proc.exitValue();
throw new IOException("script died with status " + exit);
}
catch (IllegalThreadStateException e) {
// script has not exited - assume it is now running
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
// etc
Although that 100 is very much a magic number.
To be honest, i think your best bet is just to start writing your data to
the script, and catch the broken pipe exception that will happen if the
script craps out.
tom
--
NO REAL THAN YOU ARE -- Ego Leonard, The Zandvoort Man