I am encountering some weird behavior when calling a shell script from a Java process.
Process p = Runtime.getRuntime().exec("mybashscript.sh");
(new StreamGobblerThread(p.getInputStream())).start();
(new StreamGobblerThread(p.getErrorStream())).start();
p.waitFor();
returnValue = p.exitValue();
The StreamGobblerThread just has a run() method that does a
while(((inputStream.available>0) { inputStream.skip(available); }
About 20% of the time this works, but mostly the script fails with a return code of 141 right away.
From what I found on google, 141 is a return code when a SIGPIPE was received.
Any ideas?
I'm not 100% sure what the problem, but first of all:
while(((inputStream.available>0) { inputStream.skip(available); }
isn't valid.
This is because inputStream.available() isn't blocking, so if it doesn't have anything to read immediately, it's not going to read anything at all.
You're better off having something like this:
byte[] buf = new byte[8192];
int next;
try {
while ((next = in.read(buf)) != -1) {}
} catch (IOException e) {
throw new GroovyRuntimeException("exception while dumping process stream", e);
}
read() is blocking so, this way it actually will continue reading until the stream is properly closed.
(Note: This code is from Groovy's implementation of consumeProcessOutput()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With