Re: Runtime.exec(cmd) hangs up
"Vic" <vikrantp@gmail.com> wrote in message
news:1180122190.487170.204980@a35g2000prd.googlegroups.com...
Alright so here is my new code now, I implemented it the way you said
(with some online help)
class StreamGobbler extends Thread {
InputStream is;
String type;
StreamGobbler(InputStream is, String type){
this.is = is;
this.type = type;
}
public void run(){
try{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line = br.readLine()) != null){
System.out.println(type+">"+line);
}
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
class CommandExecuter {
public static String stdout = null;
public static String stderr = null;
private String line;
public CommandExecuter (String cmd) throws java.io.IOException{
System.out.println("CommandExecuter: EXECUTING COMMAND: "+cmd);
Process proc = Runtime.getRuntime().exec(cmd);
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(),"ERROR");
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(),"OUTPUT");
errorGobbler.start();
outputGobbler.start();
try{
//VicP - temporary code to check the process status
int val = proc.waitFor();
//proc.wait(120000);
}
catch (Throwable t){
t.printStackTrace();
}
}
}
But now the question is how do I set the value of stdout and stderr in
CommandExecuter(As we are doing the stuff in thwo different threads
now)? I need these values as they are checked in the calling function
(which calls the Command executer constructor). Could you please
suggest me some changes to get this?
Have your StreamGobbler class keep track of the characters it's read, much
as your original code did, and add a method to return the result, something
like (not tested or even compiled)
class StreamGobbler extends Thread {
InputStream is;
String type;
String read;
StreamGobbler(InputStream is, String type){
this.is = is;
this.type = type;
}
public String getResult() {
return result;
}
public void run(){
StringBuffer buffer = new StringBuffer();
try{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line = br.readLine()) != null){
buffer.append(line);
buffer.append("\n");
}
}
catch(IOException ioe){
ioe.printStackTrace();
}
finally {
result = buffer.toString();
}
}
}
In the main program, do the following:
// wait for process to stop
int val = proc.waitFor();
// wait for threads to finish reading output
outputGobbler.join();
errorGobbler.join();
// get output
stdout = outputGobbler.getResult();
stderr = errorGobbler.getResult();