| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -11,12 +11,13 @@ | |||
| 11 | 11 | import org.apache.commons.exec.ExecuteException; | |
| 12 | 12 | import org.apache.commons.exec.ExecuteWatchdog; | |
| 13 | 13 | import org.apache.commons.exec.PumpStreamHandler; | |
| 14 | + import org.apache.commons.exec.ShutdownHookProcessDestroyer; | ||
| 14 | 15 | ||
| 15 | 16 | public class ExecTest | |
| 16 | 17 | { | |
| 17 | 18 | public static void main(String[] args) | |
| 18 | 19 | { | |
| 19 | - String line = "ping 127.0.0.1"; | ||
| 20 | + String line = "ping -n 5 127.0.0.1"; | ||
| 20 | 21 | CommandLine cmdLine = CommandLine.parse(line); | |
| 21 | 22 | ||
| 22 | 23 | DefaultExecutor executor = getExecutor(); | |
@@ -75,12 +76,18 @@ private static DefaultExecutor getExecutor() | |||
| 75 | 76 | { | |
| 76 | 77 | DefaultExecutor executor = new DefaultExecutor(); | |
| 77 | 78 | ||
| 78 | - // 设置超时时间,超时后,kill执行命令行的进程,再抛异常ExecuteException | ||
| 79 | + // 设置超时时间,超时后,ExecuteWatchdog.timeoutOccured(Watchdog w)调用Process.destroy()杀死命令行进程,类似于kill命令,但是此时命令行进程的返回值是不可信的,就是说无法确认是程序正常执行完毕,返回了一个值,还是因为超时返回了一个值。为了区分是否超时,可以配合使用DefaultExecuteResultHandler.waitFor(long timeout)进行区分,具体操作是:假设外界要求的超时时间是60秒,那么watchdog设置成60+10秒,waitFor参数设置成60秒,这样就能做到可以区分是否超时,并在超时后杀死命令行进程。 | ||
| 80 | + // 通过测试发现: | ||
| 81 | + // (1)在window上:命令行进程被Process.destroy()杀死,返回值为1;在任务管理器被结束进程杀死,返回值为1。 | ||
| 82 | + // (2)在linux(suse)上:命令行进程被Process.destroy()杀死,返回值为143;在任务管理器被结束进程杀死,返回值为137。 | ||
| 79 | 83 | ExecuteWatchdog watchdog = new ExecuteWatchdog(20 * 1000L); | |
| 80 | 84 | executor.setWatchdog(watchdog); | |
| 81 | 85 | ||
| 82 | - // 设置期望返回值,不符合抛异常ExecuteException | ||
| 83 | - executor.setExitValue(0); | ||
| 86 | + // 设置期望返回值,不符合抛异常ExecuteException。这里置为空,禁用此功能,由业务自己处理返回值,无需业务捕获异常。 | ||
| 87 | + executor.setExitValues(null); | ||
| 88 | + | ||
| 89 | + // 设置关闭钩子,当jvm退出时,杀死正在执行的命令行进程 | ||
| 90 | + executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); | ||
| 84 | 91 | ||
| 85 | 92 | return executor; | |
| 86 | 93 | } | |
| Back | FazBrowse Home | New Git URL |
0 commit comments