Java进程永远不会停止

时间:2012-12-18 10:04:00

标签: java process

我正在尝试从我的Java应用程序执行一个进程,当我从控制台执行此过程时它正常工作,但是当我执行getRuntime()。exec()时它会启动但永远不会结束,没有异常,没有退出值。 我试图执行的过程是pdftops.exe,一个将PDF文件转换为PostScript的应用程序。 当我尝试转换小文件(从Java执行)时,它工作正常,问题是转换较大的PDF可能需要更长的时间(从20秒到60秒)。我认为问题可能是执行时间太长。 以下是调用程序的代码段(命令行已简化,input.pdf和output.ps放在我的主目录中的文件夹中,pdftops.exe放在Desktop中):

String comando = "pdftops.exe input.pdf output.ps";
System.out.println("Executing "+comando);
try {
    Process pr = Runtime.getRuntime().exec(comando);            
    pr.waitFor();      
    System.out.println("Finished");
}
catch (IOException ex){
    ex.printStackTrace();
}
catch(InterruptedException ex){
    ex.printStackTrace();
}

编辑:读取进程'ErrorStream解决了问题:

try {
    System.out.println(comando);
    Process process = Runtime.getRuntime().exec(comando);            

    String line;

    InputStream stderr = process.getErrorStream ();

    BufferedReader reader = new BufferedReader (new InputStreamReader(stderr));

    line = reader.readLine();
    while (line != null && ! line.trim().equals("--EOF--")) {
        System.out.println ("Stdout: " + line);
        line = reader.readLine();
    }
}
catch (IOException ex){
    ex.printStackTrace();
}

3 个答案:

答案 0 :(得分:4)

不能立即回答您的问题,但可能有助于捕获流程的错误/输出流,以便您知道那里发生了什么(假设它产生了某些东西)。

使用java 7,您可以使用非常方便ProcessBuilder并将错误流合并到输出中...

例如,它可以等待一些输入吗?

答案 1 :(得分:2)

我会使用ProcessBuilder(类似于Jan先前所说的),如果您使用Java 5,至少下面的内容可能会告诉您错误是什么......

public void execute () throws IOException, InterruptedException
{
    ProcessBuilder pb = new ProcessBuilder("pdftops.exe", "input.pdf", "output.ps");

    Process process = pb.start();

    System.out.println("Error stream:");
    InputStream errorStream = process.getErrorStream();
    printStream(errorStream);

    process.waitFor();

    System.out.println("Output stream:");
    InputStream inputStream = process.getInputStream();
    printStream(inputStream);
}

private void printStream (InputStream stream) throws IOException
{
    BufferedReader in = new BufferedReader(new InputStreamReader(stream));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
}

答案 2 :(得分:0)

如果您浏览java文档,您会发现:

waitFor : Causes the current thread to wait, if necessary, until the process represented by this 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.
Returns: the exit value of the subprocess represented by this Process object. By convention, the value 0 indicates normal termination.
Throws: InterruptedException - if the current thread is interrupted by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.

我的猜测是,对于大文件来说,它会遇到一个困扰执行的时间难题。你可以在这里检查执行过程的完成状态,如下所示:

  if(Process.exitValue()==0)
  break;

这将确保一旦执行结束,无限或过度激进的循环将不会是执行的最终结果。