kajarigd
kajarigd

Reputation: 1309

Need to kill a Java program started by Runtime.getRuntime().exec()

In a Java program I am running another Java program using the following command:

Process p = Runtime.getRuntime().exec("echo.bat | java -Xms64M -Xmx1G -cp "+execFilePath+" "+inputFileName+" "+inputParam); 

The invocation is working fine, but if due to bad coding the executed Java file (inputFileName) is hanging, say, due to some infinite loop, a new process which got started, is not ending. Now, I need to kill that process in my code.

I am able to detect if the Java program is hanging by using TimeOut. But, I don't know how to get the process id of this executed Java program and kill it once TimeOut happens.

Any help is appreciated!

Upvotes: 1

Views: 849

Answers (1)

king_nak
king_nak

Reputation: 11513

Generally, you can call destroy on your Process instance. See here

I notice however that you are starting one process and pipe its output to another. The simple approach will most probabely only kill the former (your echo.bat process).

Therefore, you need a more complex scenario. Do the following:

  1. Start a process calling echo.bat only
  2. Wait until it is finished
  3. Read all of its output through its output stream (Process.getOutputStream())
  4. Start another process, calling the java program only.
  5. Write the read data to its input (write to Process.getInputStream())
  6. This second process instance will be your java process

As fge mentioned above, take a look at ProcessBuilder, as it simplyfies some of the steps. Especially setting up the input stream can be accomplished before actually starting the program

Upvotes: 2

Related Questions