Set timeout for process. waitfor

Source: Internet
Author: User

Java uses runtime.getruntime(cmd.exe C (command) to call the system command
Generally, process. waitfor () is called to wait until the command execution ends and obtain the execution result.
Today's tragic facts prove
Even if a simple script command is called
After process. waitfor () is called, endless or close to endless blocking may also occur.
After the fault is handled, the problem persists.
Decided to add timeout control to the code
However, process. waitfor () does not support timeout settings.
One method is to use the non-blocking process. exitvalue () method.
Then round robin checks the Process status. This method consumes more CPU resources.
So that the polling interval cannot be set too small, but it is not perfect.
There are multiple threads.
Control by other timeout mechanisms
The code used is as follows:


Public class processutils {/*** run an external command and return the status. if the specified timeout is exceeded, throw timeoutexception * @ Param command * @ Param timeout * @ return * @ throws ioexception * @ throws interruptedexception * @ throws timeoutexception */public static int executecommand (final string command, final long timeout) throws ioexception, interruptedexception, timeoutexception {Process = runtime.getruntime(cmd.exe C (command); worker Worker = new worker (process); worker. Start (); try {worker. Join (timeout); If (worker. Exit! = NULL) {return worker. exit;} else {Throw new timeoutexception () ;}} catch (interruptedexception ex) {worker. interrupt (); thread. currentthread (). interrupt (); throw ex;} finally {process. destroy () ;}} Private Static class worker extends thread {private final process; private integer exit; private worker (Process) {This. process = process;} public void run () {try {exit = process. waitfor ();} catch (interruptedexception ignore) {return ;}}}}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.