ProcessBuilder waitFor 調用外部應用


小程序項目最初使用ffmpeg轉換微信錄音文件為wav格式,再交給阿里雲asr識別成文字。視頻音頻轉換最常用是ffmpeg。

1
ffmpeg -i a.mp3 b.wav

相關文章:

問題變成怎樣使用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類實現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM