ProcessBuilder getOutputStream和相互作用进程
题
我有麻烦的相互作用过程中使用getOutputStream.这里是我的代码:
Process p = null;
ProcessBuilder pb = new ProcessBuilder("/home/eric/this.sh");
pb.directory(new File("/home/eric/"));
p = pb.start();
InputStream in = null;
OutputStream outS = null;
StringBuffer commandResult = new StringBuffer();
String line = null;
int readInt;
int returnVal = p.waitFor();
in = p.getInputStream();
while ((readInt = in.read()) != -1)
commandResult.append((char)readInt);
outS = (BufferedOutputStream) p.getOutputStream();
outS.write("Y".getBytes());
outS.close();
System.out.println(commandResult.toString());
in.close();
这里是输出:
Reading package lists...
Building dependency tree...
Reading state information...
The following packages were automatically installed and are no longer required:
libmono2.0-cil libmono-data-tds2.0-cil libmono-system-data2.0-cil
libdbus-glib1.0-cil librsvg2-2.18-cil libvncserver0 libsqlite0
libmono-messaging2.0-cil libmono-system-messaging2.0-cil
libmono-system-data-linq2.0-cil libmono-sqlite2.0-cil
libmono-system-web2.0-cil libwnck2.20-cil libgnome-keyring1.0-cil
libdbus1.0-cil libmono-wcf3.0-cil libgdiplus libgnomedesktop2.20-cil
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
firefox-globalmenu
Suggested packages:
firefox-gnome-support firefox-kde-support latex-xft-fonts
The following NEW packages will be installed:
firefox firefox-globalmenu
0 upgraded, 2 newly installed, 0 to remove and 5 not upgraded.
Need to get 15.2 MB of archives.
After this operation, 30.6 MB of additional disk space will be used.
Do you want to continue [Y/n]? Abort
this.sh 简单地运行"gksudo易于得到安装火狐"
我不知道为什么这是终止和不采取我输入"Y"的感谢。
解决方案
有几个问题。
第一: gksudo(1)
做一些肮脏的非标准技巧标准输入和输出标准的命令开始。失败的可怕的。一个很好的例子是这个命令行:
$ echo foo | gksudo -g cat
我期望任何输出和终止的 cat
尽快的 echo
已经传送的数据。不。既 gksudo
和 cat
挂在永远。没有输出。
你用例会
echo y |gksudo apt-get install ....
并且这将不会的工作。只要这不是解决的,你可以忘记做任何遥控制,如果在启动程序需要的任何用户输入。
第二:正如已经指出的那样,罗杰 waitFor()
等待终止命令。这不会发生的任何时间很快就没有任何用户输入和与gksudo问题。
第三 后搡 waitFor
下一位有下一个拦截器:你等待的 完整的 产出的过程,包括EOF.这不会很快(见"第一"和"第二").
第四 只有在这个过程已经死了的两倍(见"第二"和"第三"),它可能会有一些输入您的 Y
(可能还需要额外的 \n
).
而不是解决这些问题可能有一个更好的和更容易的方式:不要试图控制 apt-get install
标准输入。只要给它一些适当的选择其自动"答案"您的问题。一个快速的 man apt-get
变成了某些候选人:
-y, --yes, --assume-yes
--force-yes
--trivial-only
--no-remove
--no-upgrade
请参阅本手册的详细信息。
我认为这是更好的和更稳定的方式。
PS:现在我pi***o*** gksudo
相当多,所以原谅的咆哮之上。
不隶属于 StackOverflow