为什么这段代码没有给我bash提示?我已经尝试了BufferedReaders,但没有帮助.我也无法在控制台中输入任何命令,例如’help’.
>诸如“ ls”和“ ps”之类的命令可以正常工作.
>使用错误的参数或’–help’运行bash会产生输出.
>以超级用户身份运行Java没有帮助.
有任何想法吗?
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();
}
}
}
解决方法:
Why doesn’t this code give me the bash prompt?
目前尚不清楚“ bash提示符”是什么意思……但是我假设您期望在shell的标准输出/错误流上看到bash提示符字符.
无论如何,原因是外壳不是交互式的.
bash手动输入说明:
An interactive shell is one started without non-option arguments and without the -c option whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state.
请注意,当您在Linux / Unix上从Java启动命令时(按照您的操作方式),其标准I / O流将是管道,并且isatty不会将其识别为“终端”.
因此,如果要强制外壳为“交互式”,则需要在bash命令行上包括“ -i”选项.例如:
Process p = Runtime.getRuntime().exec(new String[]{"bash", "-i"});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。