views:

37

answers:

1

Hi,

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

A: 

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.

Aaron Digulla
Hi Aaron, firstly - thanks for the reply. Can you explain this in some more detail please? I've looked at many examples of what I'm trying to do and they all pretty much say the same thing. How would I use the getOutputStream? Sorry for the stupid question but I'm still quite new to all this
Wilko
Sorry, forgot the ".close()" :-) The problem is that the child process reads from stdin (== parent's output stream). It will terminate when the stream is closed. Also don't forget to call "waitFor()". This will clean up the process if it has become a "zombie" process.
Aaron Digulla
Thanks again for your response Aaron. I will give this a go :)
Wilko