ProcessBuilder.start()
和 Runtime.exec
方法創建一個本機進程。並返回 Process
子類的一個實例,該實例可用來控制進程並獲得相關信息。Process
類提供了執行從進程輸入、執行輸出到進程、等待進程完成、檢查進程的退出狀態以及銷燬(殺掉)進程的方法。Runtime
that
allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime
method. getRuntime()方法來獲取一個Runtime實例。
1.3執行一條shell命令
String commend=".....";//一條shell命令
Process pro=Runtime.getRuntime().exec(commend);
//exec方法會返回一個單獨的進程用來管理子進程(
A
new Process
object
for managing the subprocess)。 pro.waitFor()
;//導致當前線程等待,如有必要,一直要等到由該
Process
對象表示的進程已經終止。(causes
the current thread to wait, if necessary, until the process represented by this Process
object has
terminated.)也可以意味着命令運行成功,沒有發生堵塞。eg: echo "hello world" > /home/admin/newFile.txt
ls -e | grep java
需要使用如下的調用方式
String []cmdArray = new String[]{ "/bin/sh", "-c", "ls -e | grep java"};
Runtime.getRuntime().exec(cmdArray);
1.4 .2. 永遠要在調用waitFor()方法之前讀取數據流
永遠要先從標準錯誤流中讀取,然後再讀取標準輸出流
1.4 .3. 另外一個需要注意的地方是:
如果調用的腳本中存在像sudo這樣的需要tty的命令時,使用
String []cmdArray = new String[]{ "/bin/sh", "-c", "yourscriptname"};
這樣的調用方式,會爲腳本執行創建出一個tty環境,否則,運行過程會提示"sorry, you must have a tty to run xxx"的錯誤