我有一个控制台 Java 程序,它在一个单独的进程中执行 sh -i
并在进程的输入/输出流和相应的系统流之间复制数据:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
class StreamCopier implements Runnable {
private InputStream in;
private OutputStream out;
public StreamCopier(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
public void run() {
try {
int n = 0;
byte[] buffer = new byte[4096];
while (-1 != (n = in.read(buffer))) {
out.write(buffer, 0, n);
out.flush();
}
} catch (IOException e) {
System.out.println(e);
}
}
}
public class Test {
public static void main(String[] args)
throws IOException, InterruptedException {
Process process = Runtime.getRuntime().exec("sh -i");
new Thread(new StreamCopier(
process.getInputStream(), System.out)).start();
new Thread(new StreamCopier(
process.getErrorStream(), System.err)).start();
new Thread(new StreamCopier(
System.in, process.getOutputStream())).start();
process.waitFor();
}
}
在 Linux 下运行结果如下:
$
[1]+ Stopped java -cp . Test
谁能解释一下应用程序停止的原因以及如何避免?
这与我的question on copying streams有关, 但我认为这个特殊问题值得单独关注。
最佳答案
您可以通过像 sh -i +m
这样调用 shell 来关闭作业控制,这将阻止它接管 tty。这意味着 fg
和 bg
命令将不起作用,Ctrl+Z 将暂停您的 Java 应用程序、shell 和所有从它启动的程序。
如果你仍然想要作业控制,你应该使用伪终端与 shell 通信,这会创建一个新的 tty 供 shell 使用,但我认为 Java 不支持。
关于java - 为什么使用重定向的输入/输出流执行交互过程会导致应用程序停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4179052/