Runtime.getRuntime().exec()和ProcessBuilder都能啟動子程序。ProcessBuilder waitFor阻塞等待子程序執行傳回。ProcessBuilder.command()要傳入字元串list,否則啟動報錯“CreateProcess error=2 系統找不到指定的檔案”。ProcesBuilder redirect重定向流。ProcessImpl是Process的實作類。
小程式項目最初使用ffmpeg轉換微信錄音檔案為wav格式,再交給阿裡雲asr識别成文字。視訊音頻轉換最常用是ffmpeg。
相關文章:
問題變成怎樣使用java調用系統的ffmpeg工具。在java中,封裝了程序Process類,可以使用
Runtime.getRuntime().exec()
或者
ProcessBuilder
建立程序。
從Runtime.getRuntime().exec()說起
最簡單啟動程序的方式,是直接把完整的指令作為
exec()
的參數。
1
2
3
4
5
6
7
| try {
log.info("ping 10 times");
Runtime.getRuntime().exec("ping -n 10 127.0.0.1");
log.info("done");
} catch (IOException e) {
e.printStackTrace();
}
|
輸出結果
1
2
| 17:12:37.262 [main] INFO com.godzilla.Test - ping 10 times
17:12:37.272 [main] INFO com.godzilla.Test - done
|
我期望的是執行指令結束後再列印done,但是明顯不是。
waitFor阻塞等待子程序傳回
Process類提供了
waitFor
方法。可以阻塞調用者線程,并且傳回碼。0表示子程序執行正常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| /**
* Causes the current thread to wait, if necessary, until the
* process represented by this {@code Process} object has
* terminated. This method returns immediately if the subprocess
* has already terminated. If the subprocess has not yet
* terminated, the calling thread will be blocked until the
* subprocess exits.
*
* @return the exit value of the subprocess represented by this
* {@code Process} object. By convention, the value
* {@code 0} indicates normal termination.
* @throws InterruptedException if the current thread is
* {@linkplain Thread#interrupt() interrupted} by another
* thread while it is waiting, then the wait is ended and
* an {@link InterruptedException} is thrown.
*/
public abstract int waitFor() throws InterruptedException;
|
1
2
3
4
5
6
7
8
9
10
11
12
| try {
log.info("ping 10 times");
Process p = Runtime.getRuntime().exec("ping -n 10 127.0.0.1");
int code = p.waitFor();
if(code == 0){
log.info("done");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
|
輸出結果
1
2
| 17:15:28.557 [main] INFO com.godzilla.Test - ping 10 times
17:15:37.615 [main] INFO com.godzilla.Test - done
|
似乎滿足需要了。但是,如果子程序發生問題一直不傳回,那麼java主程序就會一直block,這是非常危險的事情。
對此,java8提供了一個新接口,支援等待逾時。注意接口的傳回值是boolean,不是int。當子程序在規定時間内退出,則傳回true。
1
| public boolean waitFor(long timeout, TimeUnit unit)
|
測試代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| try {
log.info("ping 10 times");
Process p = Runtime.getRuntime().exec("ping -n 10 127.0.0.1");
boolean exit = p.waitFor(1, TimeUnit.SECONDS);
if (exit) {
log.info("done");
} else {
log.info("timeout");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
|
輸出結果
1
2
| 17:43:47.340 [main] INFO com.godzilla.Test - ping 10 times
17:43:48.352 [main] INFO com.godzilla.Test - timeout
|
擷取輸入、輸出和錯誤流
要擷取子程序的執行輸出,可以使用Process類的
getInputStream()
。類似的有
getOutputStream()
、
getErrorStream()
。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| try {
log.info("ping");
Process p = Runtime.getRuntime().exec("ping -n 1 127.0.0.1");
p.waitFor();
BufferedReader bw = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK"));
String line = null;
while ((line = bw.readLine()) != null) {
System.out.println(line);
}
bw.close();
log.info("done")
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
|
注意,GBK是Windows平台的字元編碼。
輸出結果
1
2
3
4
5
6
7
8
9
10
| 18:28:21.396 [main] INFO com.godzilla.Test - ping
正在 Ping 127.0.0.1 具有 32 位元組的資料:
來自 127.0.0.1 的回複: 位元組=32 時間<1ms TTL=128
127.0.0.1 的 Ping 統計資訊:
資料包: 已發送 = 1,已接收 = 1,丢失 = 0 (0% 丢失),
往返行程的估計時間(以毫秒為機關):
最短 = 0ms,最長 = 0ms,平均 = 0ms
18:28:21.444 [main] INFO com.godzilla.Test - done
|
這裡牽涉到一個技術細節,參考Process類的javadoc
1
2
3
4
5
6
7
8
9
10
11
12
| * <p>By default, the created subprocess does not have its own terminal
* or console. All its standard I/O (i.e. stdin, stdout, stderr)
* operations will be redirected to the parent process, where they can
* be accessed via the streams obtained using the methods
* {@link #getOutputStream()},
* {@link #getInputStream()}, and
* {@link #getErrorStream()}.
* The parent process uses these streams to feed input to and get output
* from the subprocess. Because some native platforms only provide
* limited buffer size for standard input and output streams, failure
* to promptly write the input stream or read the output stream of
* the subprocess may cause the subprocess to block, or even deadlock.
|
翻譯過來是,子程序預設沒有自己的stdin、stdout、stderr,涉及這些流的操作,到會重定向到父程序。由于平台限制,可能導緻緩沖區消耗完了,導緻阻塞甚至死鎖!
網上有的說法是,開啟2個線程,分别讀取子程序的stdout、stderr。
不過,既然說是
By default
,就是有非預設的方式,其實就是使用
ProcessBuilder
類,重定向流。此功能從java7開始支援。
ProcessBuilder和redirect
1
2
3
4
5
6
7
8
| try {
log.info("ping");
Process p = new ProcessBuilder().command("ping -n 1 127.0.0.1").start();
p.waitFor();
log.info("done")
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
|
輸出結果
1
2
3
4
5
6
7
8
9
10
| 19:01:53.027 [main] INFO com.godzilla.Test - ping
java.io.IOException: Cannot run program "ping -n 1 127.0.0.1": CreateProcess error=2, 系統找不到指定的檔案。
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at com.godzilla.Test.main(Test.java:13)
Caused by: java.io.IOException: CreateProcess error=2, 系統找不到指定的檔案。
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
at java.lang.ProcessImpl.start(ProcessImpl.java:137)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 1 more
|
此處有坑:ProcessBuilder的command清單要用字元串數組或者list形式傳入! ps. 在小程式項目上,一開始把
ffmpeg -i a.mp3 b.wav
傳入ProcessBuilder,卻看不到生成的wav檔案,查了日志
CreateProcess error=2, 系統找不到指定的檔案。
還以為是ffmpeg路徑問題。後來查了api才發現掉坑了。
正确的寫法
1
| Process p = new ProcessBuilder().command("ping", "-n", "1", "127.0.0.1").start();
|
剛才說的重定向問題,可以這樣寫
1
2
3
| Process p = new ProcessBuilder().command("ping", "-n", "1", "127.0.0.1")
.redirectError(new File("stderr.txt"))
.start();
|
工作目錄
預設子程序的工作目錄繼承于父程序。可以通過
ProcessBuilder.directory()
修改。
一些代碼細節
ProcessBuilder.Redirect
java7增加了
ProcessBuilder.Redirect
抽象,實作子程序的流重定向。Redirect類有個Type枚舉
1
2
3
4
5
6
7
| public enum Type {
PIPE,
INHERIT,
READ,
WRITE,
APPEND
};
|
其中
- PIPE: 表示子流程IO将通過管道連接配接到目前的Java程序。 這是子程序标準IO的預設處理。
- INHERIT: 表示子程序IO源或目标将與目前程序的相同。 這是大多數作業系統指令解釋器(shell)的正常行為。
對于不同類型的Redirect,覆寫下面的方法
- append
- appendTo
- file
- from
- to
Runtime.exec()的實作
Runtime類的exec()底層也是用ProcessBuilder實作
1
2
3
4
5
6
7
| public Process exec(String[] cmdarray, String[] envp, File dir)
throws IOException {
return new ProcessBuilder(cmdarray)
.environment(envp)
.directory(dir)
.start();
}
|
ProcessImpl
Process的底層實作類是ProcessImpl。
上面講到流和Redirect,具體在
ProcessImpl.start()
方法
1
2
3
| FileInputStream f0 = null;
FileOutputStream f1 = null;
FileOutputStream f2 = null;
|
然後是一堆繁瑣的if…else判斷是Redirect.INHERIT、Redirect.PIPE,是輸入還是輸出流。
總結
- Process類是java對程序的抽象。ProcessImpl是具體的實作。
- Runtime.getRuntime().exec()和ProcessBuilder.start()都能啟動子程序。Runtime.getRuntime().exec()底層也是ProcessBuilder構造的
- Runtime.getRuntime().exec()可以直接消費一整串帶空格的指令。但是ProcessBuilder.command()必須要以字元串數組或者list形式傳入參數
- 預設子程序的執行和父程序是異步的。可以通過
Process.waitFor()
實作阻塞等待。 - 預設情況下,子程序和父程序共享stdin、stdout、stderr。ProcessBuilder支援對流的重定向(since java7)
- 流的重定向,是通過
ProcessBuilder.Redirect
類實作。