Process/runtime.exec() problem

i m trying to compile and run java files thru runtime.exec()...i m working on linux...when i compile a singe file it works all right....however when i compile multiple files using the same command only replacing "filename.java" by "*.java" its not working.
error: cannot read: /home/pico/example/demo/*.java
1 error
any help will be appreciated

I doubt, *.java will get replaced automatically with all your java-files. It's just treated as as file called "*.java", because resolving the wildcard is usually done by a shell which is not running when using Runtime.exec().
You have to (re)solve it yourself.
Hope this helped.

Similar Messages

  • Runtime.exec  problems

    Hi
    I would like to open a chm file from my "help" menu.
    I got two problem related to that:
    1.The first time the menu is clicked i start the process and the help is opened on top of my application frame.
    but - the second time It is opened - the only wat to recognize i sthe process is still active is to call exitValue (if it get an exception - process is still active) but - how can i make the frame on top of my application frame( the current active frame)
    2.when the application is closed the help application does not "die" with the rest of the application.
    I will be happy to get some ideas of how can i control it.
    this is my code:
    Runtime runtime=  Runtime.getRuntime();
            try {
                if(process==null){
                     process=runtime.exec(new String[] {"cmd.exe","/c" , helpLink});
                else{
                    try {
                        process.exitValue();
                        process = runtime.exec(new String[]{"cmd.exe", "/c", helpLink});
                        if (log.isDebugEnabled())
                            log.debug("process finish working");
                    } catch (IllegalThreadStateException e1) {
                        if (log.isDebugEnabled())
                            log.debug("process still working");
            } catch (IOException e1) {
                if (log.isErrorEnabled()){
                    log.error("could not open help file"+ helpLink);
                    log.error("exception:",e1);
                WorkingAreaManager.getWorkingAreaManagerInstance().displayErrorMessage(COULD_OPEN_HELP);
            }thanks,Liat

    1.The first time the menu is clicked i start the
    process and the help is opened on top of my
    application frame.
    but - the second time It is opened - the only wat to
    recognize i sthe process is still active is to call
    exitValue (if it get an exception - process is still
    active) but - how can i make the frame on top of my
    application frame( the current active frame)Sorry I don't know the answer to that. What happens if you invoke it a second time... does it bring up a completely new frame?
    2.when the application is closed the help application
    does not "die" with the rest of the application.
    I will be happy to get some ideas of how can i
    control it.process.destroy()?

  • Java.lang.Runtime.exec problem in ubuntu 9.10

    Hi:
    I tried to run some command in the java code , for example "grass64 -text /home/data/location", this command works well in the terminal, however when I call it in the java code I got some excepetions.
    My code is :
    public class Grass {
         public static String grassBatJob="GRASS_BATCH_JOB";
         public void run(String cmd,String jobPath) {
              //set the environments variables
              Map<String, String> env=new HashMap<String, String>();
              env.put(grassBatJob, jobPath);
              String gisDataBase="/home/kk/grass/GrassDataBase";
              String location="spearfish60";
              String mapset="PERMANENT";
              cmd=cmd+" "+gisDataBase+"/"+location+"/"+mapset;
              CommandLine line=new CommandLine(cmd);
              //the real cmd should be >>grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT
              System.out.println("start line=="+line.toString());
              DefaultExecutor de=new DefaultExecutor();
              try {
                   int index=de.execute(line,env);
                   System.out.println(index);
              } catch (ExecuteException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              String jobPath=Grass.class.getResource("grass.sh").getFile();
              new Grass().run("grass64 -text", jobPath);
    The real cmd I want to execute is "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT" with the envrionment variable "GRASS_BATCH_JOB=jobPath",it works well in the ternimal ,however in my application I got the exception"
    java.io.IOException: Cannot run program "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT": java.io.IOException: error=2, No such file or directory
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
         at java.lang.Runtime.exec(Runtime.java:593)
         at org.apache.commons.exec.launcher.Java13CommandLauncher.exec(Java13CommandLauncher.java:58)
         at org.apache.commons.exec.DefaultExecutor.launch(DefaultExecutor.java:246)
         at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:302)
         at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:149)
         at org.kingxip.Grass.run(Grass.java:27)
         at org.kingxip.Grass.main(Grass.java:38)
    Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
         at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
         at java.lang.ProcessImpl.start(ProcessImpl.java:65)
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
         ... 7 more
    I wonder why?

    Thanks for all of your reply, and now I can run the command, however I met some problems when I tried to get the result of the exec.
    The core codes are shown below:
    String cmd="g.version";
    String[] exe={"bash","-c",cmd};
    Process p1=Runtime.getRuntime.exec(exe,env); // the env has been set
    GrassThread outThread=new GrassThread("out", p1.getInputStream());
    outThread.start();
    GrassThread errorThread=new GrassThread("error", p1.getErrorStream());
    errorThread.start();
    int exitVal = p1.waitFor();
    String resu=outThread.sb.toString();
    System.out.println("==========the output start========");
    System.out.println(resu);
    System.out.println("==========the output end========");
    System.out.println("ExitValue: " + exitVal); //------------------> line one
    public class GrassThread extends Thread{
         public StringBuffer sb=new StringBuffer();
         public GrassThread(String type,InputStream is) {
              this.type=type;
              this.is=is;
         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);
                        sb.append(line).append("\r");  // ----------------------------> line two
    }I define a StringBuffer in the GrassThread to save the output (see the code where I marked by "line two"), and when the process complete, I check the StringBuffer to get the output (see code where I marked by "line one"), however the output in the console of the IDE are :
    ----------- output in the console of the IDE start -------------
    ==========the output start========
    ==========the output end========
    ExitValue: 0
    out>GRASS 6.4.0RC5 (2009)
    ----------output in the console of the IDE end--------------------
    I can not understand, in the code "line one", I first get the output using "System.out.println(resu);",then I print the exitvalue,but why the order of the output in the console is not what I expected?
    Another question, the code above assume the output can be got from the Process's getInputStream, however sometimes the output maybe come from the Process's getErrorStream, so how to handle it?
    Edited by: apachemaven on 2010-3-5 ??5:38

  • Runtime.exec Problem with setting environment

    Hello
    I will run a command with a new process environment. As example I take "ls". If I use the "exec(String)" method it works fine (like it should; my PATH is ...:/usr/bin:...).
    Next when I use "exec(String cmd, String[] env)" with cmd = ls and env = {PATH=} then the programm also prints out the listing of the current directory. In my opinion this shoudn't work.
    I have the problem using jdk1.2.2 (Solaris VM (build olaris_JDK_1.2.2_10, native threads, sunwjit)) on Solaris 8.
    As I understand the exec the method should work like this:
    1. fork a new Process
    2 set environment for the new process
    3 exec the new Programm in this process
    Is this statement right?
    On Solaris 2.6 the program works fine and I get an IOException.
    Some hints way the env for the process isn't set?
    Thanks
    ========================================================
    import java.io.*;
    public class Test {
    /** Version der Klasse. */
    public static final String VERSION = "$Revision:$";
    public static void main(String[] arg) {
    try {
    call("ls", new String[]{"PATH="});
    } catch (Exception ex) {
    System.out.println(ex);
    private static void call(String cmd, String[] env)
    throws Exception
    Runtime rt = Runtime.getRuntime();
    try {
    System.out.println(cmd);
    Process p = rt.exec(cmd, env);
    StreamGobbler errorGobbler = new
    StreamGobbler(p.getErrorStream(), "ERROR", System.err);
    StreamGobbler outputGobbler = new
    StreamGobbler(p.getInputStream(), "OUTPUT", System.out);
    errorGobbler.start();
    outputGobbler.start();
    try {
    p.waitFor();
    } catch (InterruptedException e) {
    if (p.exitValue() != 0) {
    throw new Exception("Process failed");
    } catch (IOException ex) {
    System.out.println("IOException: " + ex.toString());
    class StreamGobbler extends Thread {
    private InputStream m_input;
    private OutputStream m_output;
    private String m_type;
    private StringBuffer m_message;
    StreamGobbler(InputStream is, String type, OutputStream os) {
    this.m_input = is;
    this.m_output = os;
    this.m_type = type;
    this.m_message = new StringBuffer();
    outputGobbler.start();
    try {
    p.waitFor();
    } catch (InterruptedException e) {
    if (p.exitValue() != 0) {
    throw new Exception("Process failed");
    } catch (IOException ex) {
    System.out.println("IOException: " + ex.toString());
    class StreamGobbler extends Thread {
    private InputStream m_input;
    private OutputStream m_output;
    private String m_type;
    private StringBuffer m_message;
    StreamGobbler(InputStream is, String type, OutputStream os) {
    this.m_input = is;
    this.m_output = os;
    this.m_type = type;
    this.m_message = new StringBuffer();
    public synchronized void run() {
    try {
    InputStreamReader reader = new InputStreamReader(m_input);
    BufferedReader bufferedReader = new BufferedReader(reader);
    PrintWriter writer = new PrintWriter(m_output, true);
    String line = null;
    while ( (line = bufferedReader.readLine()) != null) {
    writer.println(m_type + "> " + line);
    this.m_message.append(m_type + "> " + line + "\r\n");
    } catch (IOException ioe) {
    ioe.printStackTrace();
    public synchronized String getMessage() {
    return this.m_message.toString();

    I'm having the same problem...
    Have you been able to solve your problem yet?

  • Runtime.exec--problems writing to external file

    Hi. I went to http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html, and am still quite confused regarding the use of Runtime.exec, for my purposes. I want to decompile a CLASS file using javap, and then write that to a TXT file, for easier reading/input to JAVA. Now, I use the following code (a modification of what I got from http://www.mountainstorm.com/publications/javazine.html, as the "traps" article's sample code is WAY too confusing--they say the compiler had the output sent to text.txt, without even showing how in the source code they did that), but it hangs up. Modifications to the string array cause different results, such as showing the javap help menu, or saying that the class wasn't found, but I think the way I did the array here is right:
    import java.util.*;
    import java.io.*;
    public class Test {
            try {
             String ls_str;
                String[] cmd = {"C:\\j2sdk1.4.2_04\\bin\\javap", "-c", "-classpath", "H:\\Java\\metricTest", "metricTest > blah.txt", ""};
                Process ls_proc = Runtime.getRuntime().exec(cmd);
             // get its output (your input) stream
             DataInputStream ls_in = new DataInputStream(
                                              ls_proc.getInputStream());
             try {
              while ((ls_str = ls_in.readLine()) != null) {
                  System.out.println(ls_str);
             } catch (IOException e) {
              System.exit(0);
         } catch (IOException e1) {
             System.err.println(e1);
             System.exit(1);
         System.exit(0);
    }

    Also, jesie, I realize that's what I need...the only
    problem is, the name "test.txt" is nowhere to be found
    in the source code! lolLooks like I have to explain this, then.
    When you look at a Java program you'll notice that it always has a "main" method whose signature looks like this:public static void main(String[] args)When you execute that program from the command line, it takes whatever strings you put after the class name and passes them to the main program as that array of strings. For example if you run it likejava UselessProgram foo bar hippothen the "java" command takes the three strings "foo", "bar", and "hippo" and puts them into that args[] array before calling the "main" method.
    That means that inside the "main" method in this case, "args[0]" contains "foo", "args[1]" contains "bar", and "args[2]" contains "hippo".
    Now go back to the example and see how it lines up with that.

  • Runtime exec problem with command "start"

    L.S,
    I'm working on a webservice client for uploading
    and downloading files. When a file is downloaded, it
    should be opened by the appropriate application. I
    know that this is -in theory- possible by issuing a
    start command through Runtime.getRuntime.exec():
    public void doSomething(String realName, DataHandler handler) {
      File outFile = new File(realName);
      FileOutputStream out = new FileOutputStream(outFile);
      handler.writeTo(out);
      out.close();
      String fileName = outFile.getAbsolutePath();
      Process p = Runtime.getRuntime().exec("start " + fileName);
    }Running this on my Win2000 system with J2RE 1.4.2 consistently
    fails with this message:
    java.io.IOException: CreateProcess: start C:\tmp\test.pdf error=2When I issue the exact same command from a DOS shell, Adobe
    starts up with the test document loaded. I now believe that my own
    application is somehow 'holding on to' the file, preventing an
    external application like Adobe from consuming the same file.
    Does anyone know how I can get around a problem like this? How do
    I start the appropriate application and feed it the file that was
    just downloaded by the user?

    I did a search for Runtime.exec and found some good help in this forum. Someone posted something like the following and it works pretty well.
    <<begin code>
    // Determine proper shell command (extend per OS)
    String os_name = System.getProperty("os.name");
    String shellParam "";
    if (os_name.startsWith("Windows"))
    if ( (System.getProperty("os.name").endsWith("NT")) ||
    (System.getProperty("os.name").endsWith("2000")) ||
    (System.getProperty("os.name").endsWith("XP")) )
    shell = "cmd.exe";
    } else
    shell = "command.com";
    shellParam = "/C";
    // Create a string with your program executable
    String command = "myprogram.exe";
    // Create an array of each command, I found that placing "cmd.exe /c"
    // in the same string doesn't work.
    String[] cmd_array = new String[] {
    shell,
    shellParam,
    command
    Runtime.getRuntime().exec( cmd_array );
    <<end code>>
    Do a java API search for Runtime.exec (if you use Eclipse right click and hit Open Declaration) there are ways to invoke exec that support setting of the environment as well as the current directory.

  • Runtime.exec() problem with Linux

    Hi All,
    I have a java program which I am using to launch java programs on all platforms.
    I am using the Runtime.exec() method to start the process in a separate JVM.
    But, I had a problem with the -classpath switch if the directories contained spaces. So I modified the java command which I am passing to the exec() method to something like:
    java -classpath \"./my dir with spaces\" com.harshal.MainThis I had to do because of the problem in windows. But, if I use double quotes in Linux (for the classpath switch in my exec() method), it won't work.
    Can anyone correct me so that I can use the Runtime.exec() method on all platforms to launch the java application even if the classpath directories contains spaces.
    Thank you very much.

    I was reading about the command line args on java's
    tutorial and I found a shocking news. Mac OS doesn't
    support command line args, That's news to me. Could you please elaborate ?
    More important is: I got it working. I figured out I had forgotten to try something before, or, to be more correct, I made an error when trying malcommc's envp suggestion: I used "classpath" as key, not "CLASSPATH", as it should have been.
    Ran a new test, got it working.
    Sample:
    Given a rootdir. Subdirectory "cp test" with a classfile (named "test") without package declaration. Running another class in another directory, using:
    String[] cmd = new String[]{
        "java", "test"
    String[] envp = new String[]{
        "CLASSPATH=rootdir:rootdir/cp test" // <-- without quotes.
    Runtime.getRuntime().exec(cmd, envp);It's been my wrong all the time. I didn't check hard enough. It simply had to work somehow (that's the kind of things that's easy to say afterwards :-)).

  • Runtime exec problem to execute a C program

    Hi,
    I've spend lot of time trying to find a solution without success...
    My aim is to run a C program from a java application under linux. My C code is the following:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    main(int argc, char **argv){
    printf("hello world \n");
    Once compiled I run my java application wich run the binary through a runtime.exec().
    I followed the example given by
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    with the same input gobblers and threads.
    For some reason it doesn't work: nothing comes out...
    When I call "ls" instead of my binary it works perfectly!
    WHY??
    Any help would be greatly appreciated!

    Thanks for the reply.
    Yes it seems that JNI could be a solution, but it looks a bit complicated an maybe not so well adapted to my purpose.
    The executables I want to execute from my java application don't need any arguments.
    If JNI is really the only way I'll try to use it but is there any good reason why runtime exec doesn't work? It is supposed to execute any executable isn't it?
    cheers

  • Runtime.exec problem

    we have a c program which does the encryption on the input files.
    IF we ran this program in unix os, it will take 30 secs to finish.
    But if we call this program using java by calling Runtime.getRuntime().exec(command)
    it takes 20 minutest to finish.
    We wonder why does it take this much time to finish.
    We are having thought that when the program runs in unix os it can get all the resources it want.
    but when run this through java, it is limited to JRE / JVM memory size. --->Am I right?
    Could you please clarify my doubt on the memory size. If I wrong, how can we fix this problem.
    Thanx

    In the case of unix
    u will just run the executable using a.out. For processor its just the execution of the executable, so 30 secs
    In case of java
    step1: It has to interpret the java program line by line after doing required loading, linking and initialization
    of the required libraries and class files.
    step2: It has to create a separate process using Runtime.getRuntime().exec() and wait for the result
    of that process
    so the total time will be step1 + step2 = some time + 30 sec = 20 minutes.

  • Runtime.exec() - Problem when using cvs-command

    I have a problem with the Runtime.getRuntime().exec() - Command. I try to execute a command to export files from our cvs-repository. As you hopefully know, cvs produces a lot of output.
    When I start my 'cvs export ... '- command from the console-window of windows, everything works perfect. But when I try to use the Runtime.getRuntime().exec("CVS export ...") the created cvs-subprocess stops after the export of the first three files. When I close the main-window, where the cvs-process was started from, the cvs-process continues working.
    I could see, that many others had the same problem, but I couldn't find a real solution there.
    Is there a possibility to clear/delete the output-buffer of the cvs-subprocess, because I don't really need the information, that cvs gives me. It is enough for me when cvs stores the files :-)
    My source:
    public void executableTest()
    Runtime run = Runtime.getRuntime();
    try
    Process cvsProcess = run.exec("cvs export .... ");
    cvsProcess.waitFor();
    BufferedReader in = new BufferedReader
              ( new InputStreamReader(cvsProcess.getInputStream()) );
         String line;
         while ((line = in.readLine()) != null)
              System.out.println(line);
         catch (Exception e)
         System.out.println(e.getMessage());
    Thanks for your help.

    if the buffer is overflowing, then you don't want to do the waitfor until after you've hit the end of the inputstream, me thinks.

  • Runtime exec() Problem, change working dir

    Hi!
    I have following problem:
    I want to call an executable from my home-directory under Linux this way:
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("/home/tom/prog/exec-command");
    Unfortunately I'm getting either exception "file not found" (but it's there) or no complain but no program run...
    perhaps something's wrong with the path-name?
    If I call the program in the directory with a shell it works fine.
    Would be very happy if anybody can give a hint!
    Thanks a lot,
    Manuel

    You are interested in the programs output? Does it write to stdout or stderr or both? In any case, my advice is to go multithreading and use one thread to wait for the program to exit, one to read stdout and one to read stderr. If you just use one thread for reading, the program might block. I normally use something like this:
      final int BUFFER = 2048;
      final Process p = Runtime.getRuntime().exec(args);
      //read standard out output of the external executable
      //in seperate thread to avoid I/O deadlocks
      new Thread()
        public void run()
           try
             BufferedInputStream in =  new BufferedInputStream (p.getInputStream());
             int i;
             byte[] buf = new byte[BUFFER];
             while ( (i = in.read(buf, 0, BUFFER)) != -1 )
                System.out.write(buf, 0, i);
             in.close();
           catch (IOException e)
             e.printStackTrace();
      }.start();
      //read standard error output of the external executable
      //in seperate thread for symmetry
      new Thread()
        public void run()
           try
             BufferedInputStream in =  new BufferedInputStream (p.getErrorStream());
             int i;
             byte[] buf = new byte[BUFFER];
             while ( (i = in.read(buf, 0, BUFFER)) != -1 )
                System.err.write(buf, 0, i);
             in.close();
           catch (IOException e)
             e.printStackTrace();
      }.start();
      //Wait for the external process to finish     
      int exitCode = p.waitFor();          
      if ( exitCode != 0 )
        throw new IOException("Executable stopped with error code "+exitCode); Cheers, HJK

  • Problem in Runtime.exec()

    I am trying to launch a new java application from my java program like this-:
    import java.io.*;
    public class test123{
    //String userStr="";
                public static void main(String args[]) throws Exception{
                        Process p = Runtime.getRuntime().exec("java JavaExec",null,currentDir);
                        Thread.sleep(10000);
                        System.out.println("After Destroy");
    } The JavaExec file�s code is -:
    import java.io.*;
    import org.apache.log4j.Logger;
    public class JavaExec
                 static Logger logger = Logger.getLogger("JavaExec.class");
    public static void main(String args[])
    try
                Runtime runtime = Runtime.getRuntime();
                            Process process = runtime.exec("notepad");
                int exitCode=0;
                while(true)
                            //logger.info("Inside the infinite while loop in javaexec");
                            try
                                        exitCode = process.exitValue();
                                        System.out.println(exitCode);
                                        process.destroy();
                                        process = runtime.exec("notepad");
                            catch(IllegalThreadStateException itse)
                                        System.out.println("Inside exception");
    } catch (Throwable t)
    t.printStackTrace();
    }Notepad opens when I execute the test123 class but instead of remaining open even if I close it , I am able to close notepad. The JavaExec only starts processing again when my main quits.
    Please let me know the solution to this problem.....
    Thanks in Advance
    Inder Jeet Singh

    Convoluted at best. You don't need that loop, just useexitCode = process.exitValue();and it will block until notepad exits.
    P.S. Why a Runtime.exec() executing a Java program that does a Runtime.exec() on notepad?

  • Process proc=runtime.exec("sh","-c","//home//usr//mkdir abcd") not working

    my servlet calling the above line is not executing to make a directory
    "abcd" at specified location. i am using Mandrake Linux and Tomcat... can anybody expalin the error.

    Hi raghutv,
    I also have this error
    I use Tomcat 4.0 and Window Me
    Do u think that the problem is "Window OS" or Tomcat Setting
    I have a problem. I want to complie the other Java Program "hi.java" using servlet.
    I am compiling the servlet code succesfully, but the web page can't display anything.
    The real path of "hi.java" is in the
    D:\Program Files\Apache Tomcat 4.0\FYP\WEB-INF\classes\hi.java
    This is my servlet code..............pls help.............thx!
    /*********************** Hello.java *********************/
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Hello extends HttpServlet
    public void service(HttpServletRequest req,
    HttpServletResponse res)
    throws ServletException, IOException
    try {
    String path = getServletContext().getRealPath("\\WEB-INF\\classes\\hi.java");
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec("javac.exe " + path);
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    PrintWriter com_out = res.getWriter();
    com_out.println("<pre>");
    String line = null;
    while((line = br.readLine()) != null){
    com_out.println(line);
    //String[] cmd = { "ping.exe", "time.nist.gov" }; // Command and argument
    //String[] cmd = { "javac.exe","hi.java"}; // Command and argument
    //Process process = Runtime.getRuntime().exec(cmd); // Execute command
    //Process process = Runtime.exec(cmd); // Execute command
    //process.waitFor(); // Wait until process has terminated
    catch (Exception e) {
    System.err.println(e);

  • A problem with "Runtime.exec"

    Hello!
    I'm just trying to call a Fortran executable in a Java program.
    I'm a beginner in Java language and I believed Runtime.exec was the solution. My code :
    try {
    Process process = null;
    Runtime runtime = Runtime.getRuntime();
    process = runtime.exec("<name>.exe");
    catch (IOException eio) {
    System.out.println("Error -- " + eio.toString());
    When I run the project, there's no error, but the executable is not called.
    Can anybody help me?

    process = runtime.exec("Make sure// you have the right// path to.exe");

  • Runtime.exec() fails sometime to execute a command

    Hello,
    I have a program thats using Runtime.exec to execute some external programs sequence with some redirection operators.
    For e.g, I have some command as follows;
    1 - C:\bin\IBRSD.exe IBRSD -s
    2 - C:\bin\mcstat -n @punduk444:5000#mc -l c:\ | grep -i running | grep -v grep |wc -l
    3 - ping punduk444 | grep "100%" | wc -l
    ...etc.
    These command in sequence for a single run. The test program makes multiple such runs. So my problem is sometimes the runtime.exec() fails to execute some of the commands above (typically the 2nd one). The waitFor() returns error code (-1). That is if I loop these commands for say 30 runs then in some 1~4 runs the 2nd command fails to execute and return -1 error code.
    Can some one help me out to as why this is happening? Any help is appreciated
    Thanks,
    ~jaideep
    Herer is the code snippet;
    Runtime runtime = Runtime.getRuntime();
    //create process object to handle result
    Process process = null;
    commandToRun = "cmd /c " + command;
    process = runtime.exec( commandToRun );
    CommandOutputReader cmdError = new CommandOutputReader(process.getErrorStream());
    CommandOutputReader cmdOutput = new CommandOutputReader(process.getInputStream());
    cmdError.start();
    cmdOutput.start();
    CheckProcess chkProcess = new CheckProcess(process);
    chkProcess.start();
    int retValue = process.waitFor();
    if(retValue != 0)
    return -1;
    output = cmdOutput.getOutputData();
    cmdError = null;
    cmdOutput = null;
    chkProcess = null;
    /*******************************supporting CommandOutputReader class *********************************/
    public class CommandOutputReader extends Thread
    private transient InputStream inputStream; //to get output of any command
    private transient String output; //output will store command output
    protected boolean isDone;
    public CommandOutputReader()
    super();
    output = "";
    this.inputStream = null;
    public CommandOutputReader(InputStream stream)
    super();
    output = "";
    this.inputStream = stream;
    public void setStream(InputStream stream)
    this.inputStream = stream;
    public String getOutputData()
    return output;
    public void run()
    if(inputStream != null)
    final BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream), 1024 * 128);
    String line = null;
    try
    while ( (line = bufferReader.readLine()) != null)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.DEBUG,line);
    //output += line + System.getProperty(Constants.ALL_NEWLINE_GETPROPERTY_PARAM);
    output += line + "\r\n";
    System.out.println("<< "+ this.getId() + " >>" + output );
    System.out.println("<< "+ this.getId() + " >>" + "closed the i/p stream...");
    inputStream.close();
    bufferReader.close();
    catch (IOException objIOException)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.ERROR, ResourceString.getString("io_exeception_reading_cmd_output")+
    objIOException.getMessage());
    output = ResourceString.getString("io_exeception_reading_cmd_output");
    else
    output = "io exeception reading cmd output";
    finally {
    isDone = true;
    public boolean isDone() {
    return isDone;
    /*******************************supporting CommandOutputReader class *********************************/
    /*******************************supporting process controller class *********************************/
    public class CheckProcess extends Thread
    private transient Process monitoredProcess;
    private transient boolean continueLoop ;
    private transient long maxWait = Constants.WAIT_PERIOD;
    public CheckProcess(Process monitoredProcess)
    super();
    this.monitoredProcess = monitoredProcess;
    continueLoop =true;
    public void setMaxWait(final long max)
    this.maxWait = max;
    public void stopProcess()
    continueLoop=false;
    public void run()
    //long start1 = java.util.Calendar.getInstance().getTimeInMillis();
    final long start1 = System.currentTimeMillis();
    while (true && continueLoop)
    // after maxWait millis, stops monitoredProcess and return
    if (System.currentTimeMillis() - start1 > maxWait)
    if(monitoredProcess != null)
    monitoredProcess.destroy();
    //available for garbage collection
    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
    monitoredProcess = null;
    return;
    try
    sleep(1000);
    catch (InterruptedException e)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.ERROR, ResourceString.getString("exception_in_sleep") + e.getLocalizedMessage());
    System.out.println(ResourceString.getString("exception_in_sleep") + e.getLocalizedMessage());
    else
    System.out.println("Exception in sleep" + e.getLocalizedMessage());
    if(monitoredProcess != null)
    monitoredProcess.destroy();
    //available for garbage collection
    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
    monitoredProcess = null;
    /*******************************supporting process controller class *********************************/

    Hi,
    Infact the command passed to the exec() is in the form of a batch file, which contains on of these commands. I can not put all commands in one batch file due to inherent nature of the program.
    But my main concern was that, why would it behave like this. If I run the same command for 30 times 1~3 times the same command can not be executed (returns with error code 1, on wiun2k pro) and rest times it works perfectly fine.
    Do you see any abnormality in the code.
    I ahve used the same sequence of code as in the article suggested by
    "masijade". i.e having threads to monitor the process and other threads to read and empty out the input and error streams so that the buffer does not get full.
    But I see here the problem is not of process getting hanged, I sense this because my waitFor() returns with error code as 1, had the process hanged it would not have returned , am I making sense?
    Regards,
    ~jaideep

Maybe you are looking for

  • Relatiive Path problem when using JSP:include in web portlet

    Hi I am using Oracle Portal 9.0.2, and thus OC4J as the J2EE platform. I have created a JSP web portlet that is supposed to inlude a specific static html file, which name is passed to it using a portlet parameter. It works, but I had to create a symb

  • TimeCapsule not allowing my full ISP connection speed

    Hello everyone, I pay for a 30mbps internet connection and the only way to have it is to connect my MBP directly to the RJ-45 cable. Right now, I am connected wirelessly with my 500GB TC. Would Airport Extreme or Airport express be faster? Any other

  • ABAP Certification material

    If anyone has abap certification material plz contact me. I can exchange them with the material I have in CRM or XI. [email protected]

  • Send authenticated(from java) user information to IIS

    We are using webSphere 4.0/Servlet to authenticate users and store userid/password information in session. We have a link, on the same domain, which accesses IIS server. How do we pass the user's id/password to IIS so that the user does not get to di

  • Unable to start computer.....help!

    When I try to start my imac I get a message that says, "Can't find harddrive for imac processor..g,4......" Has my harddrive died?