[英]ProcessBuilder getOutputStream and interacting with processes
我無法使用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”
我不知道為什么它是Aborting而不是我的輸入“Y”謝謝。
有幾個問題。
首先 : gksudo(1)
使用它啟動的命令的標准輸入和標准輸出做一些骯臟的,非標准的技巧。 它失敗了。 一個很好的例子是這個命令行:
$ echo foo | gksudo -g cat
一旦echo
傳遞了數據,我就會期待任何輸出和cat
的終止。 不。 gksudo
和cat
都永遠地流連。 沒有輸出。
你的用例就是
echo y |gksudo apt-get install ....
這也行不通。 只要沒有解決這個問題,如果啟動的程序需要任何用戶輸入,您就可以忘記進行任何遠程控制。
第二 :正如Roger 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 *** ***Ø gksudo
不少,所以借口上面的咆哮。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.