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

前端 未结 17 1799
长发绾君心
长发绾君心 2020-11-27 12:08

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

17条回答
  •  粉色の甜心
    2020-11-27 12:35

    Following the answer by erickson, I created a more generic way to do the same thing.

    public class ProcessWithTimeout extends Thread
    {
        private Process m_process;
        private int m_exitCode = Integer.MIN_VALUE;
    
        public ProcessWithTimeout(Process p_process)
        {
            m_process = p_process;
        }
    
        public int waitForProcess(int p_timeoutMilliseconds)
        {
            this.start();
    
            try
            {
                this.join(p_timeoutMilliseconds);
            }
            catch (InterruptedException e)
            {
                this.interrupt();
            }
    
            return m_exitCode;
        }
    
        @Override
        public void run()
        {
            try
            { 
                m_exitCode = m_process.waitFor();
            }
            catch (InterruptedException ignore)
            {
                // Do nothing
            }
            catch (Exception ex)
            {
                // Unexpected exception
            }
        }
    }
    

    Now, all you have to do is as follows:

    Process process = Runtime.getRuntime().exec("");
    ProcessWithTimeout processWithTimeout = new ProcessWithTimeout(process);
    int exitCode = processWithTimeout.waitForProcess(5000);
    
    if (exitCode == Integer.MIN_VALUE)
    {
        // Timeout
    }
    else
    {
        // No timeout !
    }
    

提交回复
热议问题