pom.xml引用:
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-execartifactId>
- <version>1.3version>
- dependency>
- import org.apache.commons.exec.*;
-
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.IOException;
- import java.util.Map;
-
- public class Main {
- private static long processId = -1;
-
- public static void main(String[] args) {
- //无止境ping,但会再下面被ExecuteWatchdog设置的超时值终止进程而中断
- CommandLine commandLine = CommandLine.parse("ping 127.0.0.1 -t");
-
- DefaultExecutor executor = new DefaultExecutor() {
- @Override
- protected Process launch(CommandLine command, Map
env, File dir) throws IOException { - Process process = super.launch(command, env, dir);
- processId = process.pid();
- System.out.println("进程id=" + processId);
- return process;
- }
- };
- executor.setExitValues(null);
-
- //如果进程运行时间超过timeOut毫秒,进程就自动结束(销毁)
- long timeOut = 5000;
- ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut);
- executor.setWatchdog(watchdog);
-
- final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
-
- PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
- executor.setStreamHandler(streamHandler);
-
- ExecuteResultHandler erh = new ExecuteResultHandler() {
- @Override
- public void onProcessComplete(int exitValue) {
- // exitValue 0 表示进程任务正常完成后结束退出。
- // exitValue非0值表示异常结束进程。
- System.out.println("exitValue:" + exitValue);
-
- try {
- String os = outputStream.toString("GBK");
- System.out.println("onProcessComplete:" + os);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void onProcessFailed(ExecuteException e) {
- e.printStackTrace();
-
- try {
- String es = errorStream.toString("GBK");
- System.out.println("onProcessFailed:" + es);
- } catch (Exception ee) {
- ee.printStackTrace();
- }
- }
- };
-
- try {
- executor.execute(commandLine, erh);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- System.out.println("end");
- }
- }
输出:
end
进程id=27652
exitValue:1
onProcessComplete:
正在 Ping 127.0.0.1 具有 32 字节的数据:
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=200
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=200
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=200
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=200
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=200