终止在 Java 中调用的子进程时出现问题
在我的程序中,我调用一个 Linux 进程,读取该进程的输出,对其进行处理,然后休眠直到下一次迭代。我遇到的问题是,即使我执行 childProcess.destroy()
,我调用的进程并不总是会终止。代码如下:
while(true) {
Process childProcess = Runtime.getRuntime().exec("./getData");
InputStream input = childProcess.getInputStream();
BufferedReader inPipe = new BufferedReader(new InputStreamReader(input));
while((lineRead = inPipe.readLine()) != null) {
// do stuff
}
childProcess.destroy();
inPipe.close();
input.close();
}
绝大多数情况下,./getData 会正常运行、退出,并且我的程序会按预期运行。但是......有时它不会退出,只是坐在那里消耗CPU。我需要一种方法来消灭它。我还尝试在调用它之前添加它,但这不起作用:
Process killGetData = Runtime.getRuntime().exec("pkill -9 getData");
killGetData.destroy();
我猜测也许我陷入了内部 while() 循环中。
如有任何想法、意见和建议,我们深表谢意。预先非常感谢
约翰
From within my program, I invoke a Linux process, read the output from that process, process it and then sleep until the next iteration. The problem I'm having is that the process I call doesn't always die, even when I do a childProcess.destroy()
. Here's the code:
while(true) {
Process childProcess = Runtime.getRuntime().exec("./getData");
InputStream input = childProcess.getInputStream();
BufferedReader inPipe = new BufferedReader(new InputStreamReader(input));
while((lineRead = inPipe.readLine()) != null) {
// do stuff
}
childProcess.destroy();
inPipe.close();
input.close();
}
The vast majority of the time, ./getData runs, exits gracefully and my program works as it should. But....sometimes it doesn't exit and just sits there consuming CPU. I need a way of killing it off. I also tried adding this BEFORE I invoke it but this didn't work:
Process killGetData = Runtime.getRuntime().exec("pkill -9 getData");
killGetData.destroy();
I'm guessing that perhaps I'm getting stuck in the inner while() loop.
Any thoughts, ideas and tips gratefully received. Many thanks in advance
John
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须关闭子进程的输入管道才能终止它。添加
(它是父进程的输出流,但子进程的输入)。
[编辑] 另外不要忘记调用
childProcess.waitFor()
来清理僵尸进程。You must close the input pipe to the child process to terminate it. Add
(it's an output stream for the parent process but the input for the child).
[EDIT] Also don't forget to call
childProcess.waitFor()
to clean up the zombie process.