Re: Inheriting stderr in Runtime.exec() child
On Jun 11, 8:46 pm, "John B. Matthews" <nos...@nospam.invalid> wrote:
In article
<69ea46f9-0deb-4004-bcd1-db847ad47...@o30g2000vbc.googlegroups.com>,
Alexandre Ferrieux <alexandre.ferri...@gmail.com> wrote:
[...]
However, in some cases I would like the 2 (stderr) of the child to
just inherit the caller's, as in most other environments
(C,Tcl,sh,csh...), so that stderr logging naturally ends up in the
caller's log file.
How do I do that ?
(As a workaround, I've started a thread reading from the
getErrorStream () pipe and writing to System.err, but that's
inefficient and inelegant).
A separate thread? I think System.err _is_ the inherited stderr stream,
for example:
<console>
$ java ExecTest 1>/dev/null 2>temp ; cat temp
ls: foo: No such file or directory
Exit value: 1
</console>
<code>
import java.io.*;
/** @author John B. Matthews */
class ExecTest {
public static void main (String[] args) {
String s;
try {
Process p = Runtime.getRuntime().exec(
"ls . foo");
// read from the process's stdout
BufferedReader stdout = new BufferedReader (
new InputStreamReader(p.getInputStream())=
);
while ((s = stdout.readLine()) != null) {
System.out.println(s);
}
// read from the process's stderr
BufferedReader stderr = new BufferedReader (
new InputStreamReader(p.getErrorStream())=
);
while ((s = stderr.readLine()) != null) {
System.err.println(s);
}
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
System.err.println("Exit value: " + p.waitFor());
}
catch (Exception e) {
e.printStackTrace();
}
}}
</code>
I usually keep stout and sterr separate, but I see ProcessBuilder makes
it easy to merge them:
[1]<http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html>
Ahem... I think I was unclear :}
Forget about my separate thread.
Suppose my Java process is launched this way in bash:
java myclass 2> temp
and suppose that myclass calls Runtime.exec() and that the child
writes to its stderr.
How do I arrange for the child's stderr to end up in temp as inherited
from the parent ?
Of course, the following are not allowed:
- explicit redirection 2> temp (again) in Runtime.exec's argument
- active "pump" reading from the getErrorStream like your example
-Alex