java - 使用 Java 的 Runtime.exec() 时如何添加超时值?

标签 java process timeout runtime exec

我有一种方法用于在本地主机上执行命令。我想向该方法添加一个超时参数,以便如果被调用的命令没有在合理的时间内完成,该方法将返回错误代码。这是到目前为止的样子,没有超时功能:

public static int executeCommandLine(final String commandLine,
                                     final boolean printOutput,
                                     final boolean printError)
    throws IOException, InterruptedException
{
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(commandLine);

    if (printOutput)
    {
        BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        System.out.println("Output:  " + outputReader.readLine());
    }

    if (printError)
    {
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        System.out.println("Error:  " + errorReader.readLine());
    }

    return process.waitFor();
}

谁能建议我实现超时参数的好方法?

最佳答案

如果您使用的是 Java 8 或更高版本,您可以简单地使用新的 waitFor with timeout :

Process p = ...
if(!p.waitFor(1, TimeUnit.MINUTES)) {
    //timeout - kill the process. 
    p.destroy(); // consider using destroyForcibly instead
}

关于java - 使用 Java 的 Runtime.exec() 时如何添加超时值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/808276/

相关文章:

c - 调用fork时是否复制线程?

iphone - iOS ping 和 ttl 超时

java - 用泛型类实现 Comparable

java - 如何正确理解 yarn 容器?

c# - 从 WCF 服务派生的进程变得空闲

linux - Windows/Linux 子进程标准输入差异

WCF超时客户端与服务器

timeout - 调用.php执行时间长出现 "mod_fastcgi.c.2566 unexpected end-of-file (perhaps the fastcgi process died)"如何解决?

java - 如果用 ArrayList 和 LinkedList 实现,下面的代码是怎么运行的?

java - 井字游戏,多人安卓