java native Process timeout

前端 未结 6 1459
不思量自难忘°
不思量自难忘° 2020-11-27 14:31

At the moment I execute a native process using the following:

java.lang.Process process = Runtime.getRuntime().exec(command); 
int returnCode = process.waitF         


        
6条回答
  •  旧巷少年郎
    2020-11-27 15:02

    just modified a bit according to my requirement. time out is 10 seconds here. process is getting destroyed after 10 seconds if it is not exiting.

    public static void main(String arg[]) {
    
        try {
            Process p = Runtime.getRuntime().exec("\"C:/Program Files/VanDyke Software/SecureCRT/SecureCRT.exe\"");
            long now = System.currentTimeMillis(); 
            long timeoutInMillis = 1000L * 10; 
            long finish = now + timeoutInMillis; 
            while ( isAlive( p ) ) { 
                Thread.sleep( 10 ); 
                if ( System.currentTimeMillis() > finish ) {
                    p.destroy();
                }
            }
        } catch (Exception err) {
            err.printStackTrace();
        }
    }
    
    public static boolean isAlive( Process p ) {  
        try {  
            p.exitValue();  
            return false;  
        } catch (IllegalThreadStateException e) {  
            return true;  
        }  
    }  
    

提交回复
热议问题