cod*_*der 3 java processbuilder 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();
}
Run Code Online (Sandbox Code Playgroud)
任何帮助或工作的例子都会非常有帮助
呵呵.使用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();
Run Code Online (Sandbox Code Playgroud)
我正在运行的程序只是一个包含大量sleep 1和echo行的脚本:
#!/bin/sh
sleep 1
echo "Hello"
sleep 1
echo "Hello"
...
Run Code Online (Sandbox Code Playgroud)
从进程中读取的线程Hello每隔一秒左右吐出一次.
| 归档时间: |
|
| 查看次数: |
6788 次 |
| 最近记录: |