Problems killing child process invoked in Java

丶灬走出姿态 提交于 2019-12-07 18:07:10

问题


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


回答1:


You must close the input pipe to the child process to terminate it. Add

childProcess.getOutputStream().close();

(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.



来源:https://stackoverflow.com/questions/3931231/problems-killing-child-process-invoked-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!