-->

使用进程生成或Apache公地EXEC执行外部程序(Executing an external pr

2019-09-17 08:55发布

我需要执行它返回大的数据(时间超过2小时以完成)NAND其中连续地输出数据的外部应用程序。

我需要做的是异步执行这个程序,捕捉文件中的输出。 我试图用java进程生成,但它似乎挂起,并返回只有当程序退出或强制终止输出。

我试图用进程生成和spwaned新的线程来捕获输出,但它仍然没有帮助。

然后,我了解Apache公地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();
    }

任何帮助或工作的例子对子级是非常有益的

Answer 1:

呵呵。 使用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每秒左右。



文章来源: Executing an external program using process builder or apache commons exec