Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a timeout value when using Java's Runtime.exec()?

I have a method I am using to execute a command on the local host. I'd like to add a timeout parameter to the method so that if the command being called doesn't finish in a reasonable amount of time the method will return with an error code. Here's what it looks like so far, without the ability to timeout:

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(); } 

Can anyone suggest a good way for me to implement a timeout parameter?

like image 451
James Adams Avatar asked Apr 30 '09 18:04

James Adams


People also ask

How do you create a timeout in Java?

The java. lang. Object. wait(long timeout) causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

What is process WaitFor ()?

WaitFor() Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. WaitFor(Int64, TimeUnit) Causes the current thread to wait, if necessary, until the subprocess represented by this Process object has terminated, or the specified waiting time elapses.

What is runtime getRuntime () exec?

In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.


1 Answers

If you're using Java 8 or later you could simply use the new waitFor with timeout:

Process p = ... if(!p.waitFor(1, TimeUnit.MINUTES)) {     //timeout - kill the process.      p.destroy(); // consider using destroyForcibly instead } 
like image 131
Aleksander Blomskøld Avatar answered Oct 08 '22 08:10

Aleksander Blomskøld