Problems killing a child process invoked in Java

In my program, I call the Linux process, read the output from this process, process it, and then sleep until the next iteration. The problem I am facing is that the process that I call does not always die, even when I do childProcess.destroy() . Here is 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 works, exits gracefully, and my program works as it should. But .... sometimes he does not go out and just sits there, consuming the processor. I need a way to kill him. I also tried adding this before I called it, but that didn't work:

 Process killGetData = Runtime.getRuntime().exec("pkill -9 getData"); killGetData.destroy(); 

I assume that maybe I am stuck in the inner while () loop.

Any thoughts, ideas and advice were gratefully received. Thank you very much in advance

John

+2
source share
1 answer

You must close the input channel to the child process to complete it. Add

 childProcess.getOutputStream().close(); 

(this is the output for the parent process, but the input for the child).

[EDIT] Also remember to call childProcess.waitFor() to clear the zombie process.

+1
source

All Articles