从Java运行外部程序,读取输出,允许中断
2022-09-03 05:44:21
我想从Java启动一个进程,读取其输出并获取其返回代码。但是当它正在执行时,我希望能够取消它。我从启动该过程开始:
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectErrorStream(true);
Process proc = pb.start();
如果我调用proc.waitFor(),在进程退出之前,我什么也做不了。所以我假设我需要这样的东西:
while (true) {
see if process has exited
capture some output from the process
decide if I want to cancel it, and if so, cancel it
sleep for a while
}
这是对的吗?有人可以给我一个如何在Java中做到这一点的例子吗?