How to add a timeout value when using Java's Runtime.exec()?
Posted
by James Adams
on Stack Overflow
See other posts from Stack Overflow
or by James Adams
Published on 2009-04-30T18:02:25Z
Indexed on
2010/05/24
13:11 UTC
Read the original article
Hit count: 390
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?
Thanks in advance for any suggestions!
--James
© Stack Overflow or respective owner