java - ProcessBuilder 不会停止

标签 java processbuilder

我正在尝试使用 Linux 下的 ProcessBuilder 类将 mp3 文件解码为 wav 文件。由于某种原因,该过程没有停止,因此我必须手动取消它。

有人可以给我一些提示吗?我认为引用的代码很容易重现:

import java.io.*;

public class Test {
 public static void main(String[] args) {
     try {
         Process lameProcess = new ProcessBuilder("lame", "--decode", "test.mp3", "-").start();
         InputStream is = lameProcess.getInputStream();
         FileOutputStream fileOutput = new FileOutputStream("test.wav");
         DataOutputStream dataOutput = new DataOutputStream(fileOutput);


         byte[] buf = new byte[32 * 1024];
         int nRead = 0;
         int counter = 0;
         while((nRead = is.read(buf)) != -1) {
             dataOutput.write(buf, 0, buf.length);
         }

         is.close();
         fileOutput.close();

     }
     catch (Exception e) {
         e.printStackTrace();
     }
 }
}

jstack的输出

"main" prio=10 tid=0x0000000002588800 nid=0x247a runnable [0x00007f17e2761000]
   java.lang.Thread.State: RUNNABLE
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:236)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
    - locked <0x00000000eb5b1660> (a java.io.BufferedInputStream)
    at java.io.FilterInputStream.read(FilterInputStream.java:107)
    at Test.main(Test.java:17)

最佳答案

您需要排出进程的输出流(通过 getInputStream() )和错误流(通过 getErrorStream() ),否则可能会阻塞。

引用Process documentation :

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, and even deadlock.

(适用于错误流和输出流)

您可能需要在不同的线程中排出每个流,因为每个流在没有数据时可能会阻塞。

关于java - ProcessBuilder 不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7561503/

相关文章:

java - 如何将服务传递给 EmptyInterceptor 类?

java - 初始化复杂过滤器时出错。从 Kotlin 运行 ffmpeg 时出现无效参数错误

java - Linux 从 Java 控制台应用程序中杀死 Java 进程

java - 如何在 Android 中添加和检索 Intent 数据

java - 当转换发生时(进入和退出)cordova geofence插件在后台如何在后台调用PHP文件?

java - eclipse GWT "There are no CSS files referenced"

java - 实现与 SimpleDateFormat 相等的 DateTimeFormatter Y10K 输出?

java - 使用 java ProcessBuilder 从批处理文件运行 python 脚本不起作用

java - 如何将 jar 文件输出返回给 ProcessBuilder?

java - 使用 Java ProcessBuilder 运行 native Windows .exe 产生错误::目录名称无效