繁体   English   中英

使用进程构建器或apache commons exec执行外部程序

[英]Executing an external program using process builder or apache commons exec

我需要执行一个外部应用程序,它返回大量数据(需要2个多小时才能完成)n并连续输出数据。

我需要做的是异步执行该程序并捕获文件中的输出。 我尝试使用java进程构建器,但它似乎挂起并仅在程序退出或强制终止时返回输出。

我试图使用进程构建器并spwaned一个新的线程来捕获输出,但它仍然没有帮助。

然后我读了关于apache commons exec并尝试了同样的事情。 然而,这也似乎需要很长时间并返回不同的错误代码(对于相同的输入)

CommandLine cmdLine = new CommandLine("/opt/testsimulator");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWatchdog(watchdog);
    try {
        executor.execute(cmdLine);
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

任何帮助或工作的例子都会非常有帮助

呵呵。 使用ProcessBuilder应该适用于您的配置。 例如,以下模式适用于我:

ProcessBuilder pb = new ProcessBuilder("/tmp/x");
Process process = pb.start();
final InputStream is = process.getInputStream();
// the background thread watches the output from the process
new Thread(new Runnable() {
    public void run() {
        try {
            BufferedReader reader =
                new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            is.close();
        }
    }
}).start();
// the outer thread waits for the process to finish
process.waitFor();

我正在运行的程序只是一个包含大量sleep 1echo线的脚本:

#!/bin/sh
sleep 1
echo "Hello"
sleep 1
echo "Hello"
...

从进程读取的线程每隔一秒左右吐出一个Hello

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM