tags:

views:

384

answers:

3

hi,

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

+3  A: 

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.

jleedev
And if the process close itself before 1 sec ?
tzim
And apparently i made myself not clear. Your code doesn't close my app. In my example, we are talking about infinitive loop in Sth class. So after one second there is still a working Sth that eats my CPU.
tzim
@tzim The call to `proc.destroy` will kill it. If the process might close itself, you have to grab the output in real time, instead of all at the end. But since you said there's an infinite loop in it, it shouldn't be a problem.
jleedev
This is the solution i used. But new JVM with program in infinite loop can't be stop that way. So i used some "not so pretty code". you can see how it looks like there -> http://stackoverflow.com/questions/2158429/compiling-and-running-user-code-with-javacompiler-and-classloader
tzim
+2  A: 
Runtime rt = Runtime.getRuntime();
// cmd == "cmd.exe /C java =Xms2M =Xmx16M Sth" 
Process proc = rt.exec(cmd);

(You have a typo in your cmd, you wrote "=Xms2M" instead of "-Xms2M", same for "-Xmx16M").

Never call Runtime.exec like that: you must split your 'cmd' in an array or you'll encounter lots of issues. Do it like this:

String[] sar = { "cmd.exe", "/C", "java", "-Xms2M", "-Xmx16M", "Sth" };
Runtime.getRuntime().exec( sar );
Webinator
Thank you, my cmd is a string array it was just a simplification.
tzim
A: 

You can use ProcessBuilder which returns a Process object and use it's destroy() method.

Example

stacker