在Java中分叉进程有效地重定向输入/输出/错误流
在bash脚本中,如果我执行一个“内联”执行的外部程序(即“bash”)。我的意思是,该进程不在后台进行扩展,子进程的stdin/stdout/stderr与bash脚本本身的stdin/stdout/stderr一致
如果我的bash脚本包含
#!/bin/sh
bash
用户可以运行我的脚本,在执行bash时,他可以在bash的标准输入中键入命令,并在stdout/stderr上查看命令的结果
这就是我的意思,子进程是“内联”运行的
在java中,进程是在后台进行的,因此进程。getOutputStream()/Process。getInputStream()/Process。getErrorStream不与系统“内联”。in/System。出/出系统。呃
我想在java程序中做的是重现我在执行一个进程时发生的行为,如上面的bash脚本示例所示
在谷歌搜索了几次之后,我得出了这个结论
public static void main(String[] args) throws IOException,
InterruptedException {
String[] cmdarray = {"bash"};
Process proc = Runtime.getRuntime().exec(cmdarray);
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(),
System.err);
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(),
System.out);
StreamGobbler inputGobbler = new StreamGobbler(System.in,
proc.getOutputStream());
errorGobbler.start();
outputGobbler.start();
inputGobbler.start();
int exitVal = proc.waitFor();
errorGobbler.join(); // Handle condition where the
outputGobbler.join(); // process ends before the threads finish
System.exit(exitVal);
}
class StreamGobbler extends Thread {
InputStream is;
OutputStream os;
StreamGobbler(InputStream is, OutputStream os) {
this.is = is;
this.os = os;
}
public void run() {
try {
int c;
while ((c = is.read()) != -1) {
os.write(c);
os.flush();
}
} catch (IOException x) {
throw new RuntimeException(x);
}
}
}
但是嘿,有三条线!再加上执行进程所跨越的线程
一定有更好的办法。比如:
Runtime.execForeground("bash", System.in, System.out, System.err);
或者只是:
Runtime.execForeground("bash");
它在与许多脚本语言一起工作时执行“内联”过程
另一种可能是使用非阻塞I/O将stdin/stdout/stderr复制到系统中。在单个线程中输入/输出/出错?有什么例子吗
共 (0) 个答案