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 apt-get install firefox"

我不知道为什么它是中止和不接受我的输入"Y"谢谢。

有几个问题。

First: gksudo(1)使用它启动的命令的标准输入和标准输出执行一些肮脏的,非标准的技巧。它失败得很惨。下面的命令行就是一个很好的例子:

$ echo foo | gksudo -g cat

我期望任何输出和终止cat一旦echo已经传递了数据。不。gksudocat都永远存在。没有输出。

你的用例应该是

echo y |gksudo apt-get install ....

,这也不起作用。只要这个问题没有解决,如果启动的程序需要任何用户输入,您就可以忘记进行任何远程控制。

Second:正如Roger已经指出的,waitFor()等待命令的终止。如果没有任何用户输入和gksudo问题,这不会很快发生。

第三个在将waitFor向下推了一点之后,有下一个阻塞器:您等待完成进程的输出,直到并包括EOF。这不会很快发生(参见"第一"one_answers"第二")。

第四个只有在进程已经死亡两次(参见"第二次"one_answers"第三次")之后,它才可能获得一些输入-您的Y(可能还需要额外的n)。


比起解决这一堆问题,可能有一个更好更简单的方法:不要试图用标准输入来控制apt-get install。只要给它一些适当的选项,它就会自动"回答"你的问题。快速man apt-get显示了一些候选:
-y, --yes, --assume-yes
--force-yes
--trivial-only
--no-remove
--no-upgrade

详细信息请参见手册。

我认为这是更好和更稳定的方式。

PS:现在我是pi*** o*** gksudo相当多,所以原谅上面的咆哮。

最新更新