Wednesday, 21 December 2011

Execute command line process from java with timeout

Execute command line process from java with timeout
This task use java to run command line process. After period of time, if process does not end normally, it is killed.
Execute command line using CallableProcess
Call executeCommand method with try ... catch. If exception is thrown, process does not start or end normally.
public static void executeCommand(String command, long timeoutInSeconds) throws Exception {
    ExecutorService service = Executors.newSingleThreadExecutor();
    Process process = Runtime.getRuntime().exec(command);
    try {
        Callable<Integer> call = new CallableProcess(process);
        Future<Integer> future = service.submit(call);
        int exitValue = future.get(timeoutInSeconds, TimeUnit.SECONDS);
        if (exitValue != 0) {
            throw new Exception("Process did not exit correctly");
    } catch (ExecutionException e) {
        throw new Exception("Process failed to execute", e);
    } catch (TimeoutException e) {
        throw new Exception("Process timed out", e);
    } finally {
private static class CallableProcess implements Callable {
    private Process p;

    public CallableProcess(Process process) {
        p = process;

    public Integer call() throws Exception {
        return p.waitFor();

  Protected by Copyscape Online Copyright Protection

No comments:

Post a Comment