我有一个Java程序
sh
以交互模式作为子进程。输入是从
System.in
输出被复制到
System.out
. 一切都很好,除了在运行诸如
pwd
在这个交互式shell中,输出以错误的顺序出现,例如:
$ pwd
$ /home/viz/workspace
而不是
$ pwd
/home/viz/workspace
$
区别在于在第一种情况下
$
在输出之前打印
普华永道
.
你知道为什么会发生这种情况以及如何解决吗?
代码如下:
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;
byte[] buffer = new byte[4096];
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
out.flush();
}
out.close();
}
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 +m");
Thread outThread = new Thread(new StreamCopier(
process.getInputStream(), System.out));
outThread.start();
Thread errThread = new Thread(new StreamCopier(
process.getErrorStream(), System.err));
errThread.start();
Thread inThread = new Thread(new StreamCopier(
System.in, process.getOutputStream()));
inThread.start();
process.waitFor();
outThread.join();
errThread.join();
inThread.join();
}
}