Reputation: 399
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
Upvotes: 3
Views: 1831
Reputation: 328556
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.
Upvotes: 1