为什么这段代码不给我bash提示呢?我已经尝试过BufferedReader,但是没有用,我也不能在控制台中输入诸如“帮助”之类的命令。
有什么想法吗?
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Main {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("bash");
InputStream o = p.getInputStream();
InputStream e = p.getErrorStream();
OutputStream i = p.getOutputStream();
while (true) {
if (o.available() > 0) {
System.out.write(o.read());
}
if (e.available() > 0) {
System.out.write(e.read());
}
if(System.in.available() > 0) {
i.write((char)System.in.read());
}
if(o.available() == 0 && e.available() == 0 && !p.isAlive()) {
return;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}发布于 2015-02-22 01:17:36
为什么这段代码不给我bash提示呢?
还不清楚你所说的“巴什提示”是什么意思.但我假设您希望看到shell的标准输出/错误流上的bash提示字符。
不管怎么说,原因是shell不是交互式的。
bash手册条目如下:
交互式shell是一个在没有非选项参数的情况下启动的,并且没有标准输入和错误都连接到终端(由isatty(3)确定)的-c选项,或者是使用-i选项启动的。PS1设置为$-,如果bash是交互式的,则包含i,允许shell脚本或启动文件测试此状态。
请注意,当您在Linux / Unix上(以您所做的方式)上从Java启动一个命令时,它的标准I/O流将是管道,而且isatty不会将它们识别为“终端”。
因此,如果您想要强制shell是“交互式的”,则需要在bash命令行中包含"-i“选项。例如:
Process p = Runtime.getRuntime().exec(new String[]{"bash", "-i"});https://stackoverflow.com/questions/28653244
复制相似问题