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 ;}}}}