Java killing process after a period of time

javaprocess

my code goes like this:

        Runtime rt = Runtime.getRuntime();
        // cmd == "cmd.exe /C java =Xms2M =Xmx16M Sth" 
        Process proc = rt.exec(cmd);

Now i want to kill this process after a second, and get his output and error into a string variables.

How to do that ?

In my case:
I have a infinitive loop in compiled class Sth. I'm starting it and then, after one second i want to kill it.

//I'm testing it on Win XP then Debian.

thx
Tzim

Best Answer

It will be a little tricky because once you terminate the process, its output is no longer available, so you have to grab the output before you kill it.

Thread.sleep(1000); 
InputStream in = proc.getInputStream();
byte[] data = new byte[in.available()];
in.read(data);
proc.destroy();

This is assuming that the process doesn't close itself in the meantime. If it does, the InputStream will not be available for use, and you'll wish you had been reading the data instead of twiddling your thumbs.

You'll definitely want to make this exception-safe — put the call to proc.destroy in a finally handler to ensure that the child process gets terminated.