FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

命令执行框架 · sherlock111/java-code@bcb9705 · GitHub

Repository navigation

Commit bcb9705

Browse files
committed
命令执行框架
1 parent 02be979 commit bcb9705

1 file changed

Lines changed: 11 additions & 4 deletions

File tree

  • basicKnowledge/src/com/xdc/basic/api/apache/commons/exec

‎basicKnowledge/src/com/xdc/basic/api/apache/commons/exec/ExecTest.java‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,13 @@
1111
import org.apache.commons.exec.ExecuteException;
1212
import org.apache.commons.exec.ExecuteWatchdog;
1313
import org.apache.commons.exec.PumpStreamHandler;
14+
import org.apache.commons.exec.ShutdownHookProcessDestroyer;
1415

1516
public class ExecTest
1617
{
1718
public static void main(String[] args)
1819
{
19-
String line = "ping 127.0.0.1";
20+
String line = "ping -n 5 127.0.0.1";
2021
CommandLine cmdLine = CommandLine.parse(line);
2122

2223
DefaultExecutor executor = getExecutor();
@@ -75,12 +76,18 @@ private static DefaultExecutor getExecutor()
7576
{
7677
DefaultExecutor executor = new DefaultExecutor();
7778

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。
7983
ExecuteWatchdog watchdog = new ExecuteWatchdog(20 * 1000L);
8084
executor.setWatchdog(watchdog);
8185

82-
// 设置期望返回值,不符合抛异常ExecuteException
83-
executor.setExitValue(0);
86+
// 设置期望返回值,不符合抛异常ExecuteException。这里置为空,禁用此功能,由业务自己处理返回值,无需业务捕获异常。
87+
executor.setExitValues(null);
88+
89+
// 设置关闭钩子,当jvm退出时,杀死正在执行的命令行进程
90+
executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
8491

8592
return executor;
8693
}

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL