StuckThead on Process.waitfor

Version Weblogic 9.2.1
OS: Solaris 10
We are encountering StuckThread when we are execing out to a process from within a MessageDrivenBean. The error seems to occur after high volume of JMS messages to the queue (around 3000 in a hour time frame). The stack trace of the Stuck Thread indicates the Process.waitFor is the reason for the stuck thread.
The type of processes that we are execing out too are:
- UNIX command "file" to determine file type
- McAfee virus scanning
It then appears that the JMS server restarts but the messages pending on the JMS queue are lost. We are using non-persistant queues and are required for other reasons. Using persistant queues is not an option.
Any information on how to resolve is greatly appreciated.
Below is the snippet of code.
public int execProcess(String args[])
     int lProcRetVal = -1;
     if (args.length < 1)
     myLogger.error("No Command to Be executed");
     return lProcRetVal;
     try
     Runtime rt = Runtime.getRuntime();
     Process proc = rt.exec(args);
     // Gets an inputstream to read error messages from
     // if there are any error message,
     StreamGobbler errorGobbler =
new StreamGobbler(proc.getErrorStream(), "ERROR");
     // Gets an inputstream to read stdout messages from
     // the process if there is any output.
     StreamGobbler outputGobbler =
new StreamGobbler(proc.getInputStream(), "OUTPUT");
     // NOTE: To passes data to the process use the
     // processes method proc.getOutputStream
     // Which returns an Output Stream to write to.
     // kick them off
     errorGobbler.start();
     outputGobbler.start();
     // IF the process succeeded then returns 0 any error???
     lProcRetVal = proc.waitFor();
     } catch (IOException ioe)
               SevereSystemException se = new SevereSystemException(
                         ErrorCodes.PROCESS_EXEC_PROCESS,
                         ErrorCodes.PROCESS_EXEC_ERROR, ioe);
               throw se;
     catch (InterruptedException ie) {
               WarningSystemException wse = new WarningSystemException(
                         ErrorCodes.PROCESS_EXEC_PROCESS,
                         ErrorCodes.PROCESS_EXEC_ERROR, ie);
               wse.createLog();
     return lProcRetVal;
}

You probably need to consume the output of your script before waiting. The script has filled its output buffer and is waiting for your app to empty it. The app is waiting for the script to finish. This article discusses this and other problems using exec():
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
HTH
Graeme

Similar Messages

  • Problem in "Process.waitFor()" in multithreaded application (UNIX OS)

    Hello all
    This is very urgent for me.
    I am using the follwing code to invoke the child process which calls a shell script in the unix OS,and it is going fine when runs in single thread. But if i run it as the multhreaded appln, anyone of the thread hangs in the 'Process.waitfor()' call. But sometimes all the threads are returning successfully. I am calling this code from the one or more threads. This is tested in the java1.2 and 1.3. so can u suggest me how to change the code or any way to fix up the problem.
    // the code starts
    String s[] = new String[3];
    s[0] = "/bin/sh";
    s[1] = "-c";
    s[2] = "encrypt.sh"; //some .sh filename to do the task
    Runtime runtime = Runtime.getRuntime();
    Process proc;
    proc = runtime.exec(s);
    InputStream is = proc.getInputStream();
    byte buf[] = new byte[256];
    int len;
    while( (len=is.read(buf)) != -1) {
    String s1 = new String(buf,0,len);
    System.out.println(s1);
    InputStream es = proc.getErrorStream();
    buf = new byte[256];
    while( (len=es.read(buf)) != -1) {
    String s1 = new String(buf,0,len);
    System.out.println("Error Stream : " + s1);
    // place where it hang
    retValue = proc.waitFor();
    //code ends
    i am handling the errorstream and output stream and not getting any error stream output and not printing any messages in the child process. When i synchronize the whole function, it went fine, but spoils the speed performance. I tried all the option but i could not solve the problem.
    thanks

    You're first reading all of the standard output, then reading all of the standard error. What if the process generates too much output to standard error and hangs while it waits for your program to read it? I would suggest having two threads, one which reads the standard output and the other which reads standard error.

  • Time duration for Process.waitFor() to wait.

    Can we specify the time duration for the Process.waitFor() after which it resumes?
              Runtime rt=Runtime.getRuntime();
              Process ps=rt.exec("some command");
              ps.waitFor();
    Like here if rt.exec() is taking a lot of time to execute, the ps should wait for a certain period of time for rt to execute and if rt doesnt complete within the specified time then ps should resume.

    I don't know exactly what you are doing but what about: wait(long timeout);

  • Process.getInputStream() and process.waitfor() block in web application

    Hi folks,
    i am really stuck with a problem which drives me mad.....
    What i want:
    I want to call the microsoft tool "handle" (see http://www.microsoft.com/technet/sysinternals/ProcessesAndThreads/Handle.mspx) from within my web-application.
    Handle is used to assure that no other process accesses a file i want to read in.
    A simple test-main does the job perfectly:
    public class TestIt {
       public static void main(String[] args){
          String pathToFileHandleTool = "C:\\tmp\\Handle\\handle.exe";
          String pathToFile = "C:\\tmp\\foo.txt";
          String expectedFileHandleSuccessOutput = "(.*)No matching handles found(.*)";
          System.out.println("pathToFileHandleTool:" + pathToFileHandleTool);
          System.out.println("pathToFile: " + pathToFile);
          System.out.println("expectedFileHandleSuccessOutput: " + expectedFileHandleSuccessOutput);
          ProcessBuilder builder = null;
          // check for os
          if(System.getProperty("os.name").matches("(.*)Windows(.*)")) {
             System.out.println("we are on windows..");
          } else {
             System.out.println("we are on linux..");
          builder = new ProcessBuilder( pathToFileHandleTool, pathToFile);
          Process process = null;
          String commandOutput = "";
          String line = null;
          BufferedReader bufferedReader = null;
          try {
             process = builder.start();
             // read command output
             bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
              while((line = bufferedReader.readLine()) != null) {
                 commandOutput += line;
              System.out.println("commandoutput: " + commandOutput);
             // wait till process has finished
             process.waitFor();
          } catch (IOException e) {
             System.out.println(e.getMessage());
             e.printStackTrace();
          }  catch (InterruptedException e) {
             System.out.println(e.getMessage());
             e.printStackTrace();      }
          // check output to assure that no process uses file
          if(commandOutput.matches(expectedFileHandleSuccessOutput))
             System.out.println("no other processes accesses file!");
          else
             System.out.println("one or more other processes access file!");
    } So, as you see, a simple handle call looks like
    handle foo.txtand the output - if no other process accesses the file - is:
    Handle v3.2Copyright (C) 1997-2006 Mark RussinovichSysinternals - www.sysinternals.com
    No matching handles found.
    no other processes accesses file!(Wether the file exists or not doesnt matter to the program)
    If some processes access the file the output looks like this:
    commandoutput: Handle v3.2Copyright (C) 1997-2006 Mark RussinovichSysinternals - www.sysinternals.com
    WinSCP3.exe        pid: 1108    1AC: C:\tmp\openSUSE-10.2-GM-i386-CD3.iso.filepart
    one or more other processes access file!So far, so good.........but now ->
    The problem:
    If i know use the __exact__ same code (even the paths etc. hardcoded for debugging purposes) within my Servlet-Webapplication, it hangs here:
    while((line = bufferedReader.readLine()) != null) {if i comment that part out the application hangs at:
    process.waitFor();I am absolutely clueless what to do about this....
    Has anybody an idea what causes this behaviour and how i can circumvent it?
    Is this a windows problem?
    Any help will be greatly appreciated.....
    System information:
    - OS: Windows 2000 Server
    - Java 1.5
    - Tomcat 5.5
    More information / What i tried:
    - No exception / error is thrown, the application simply hangs. Adding
    builder.redirectErrorStream(true);had no effect on my logs.
    - Tried other readers as well, no effect.
    - replaced
    while((line = bufferedReader.readLine()) != null)with
    int iChar = 0;
                  while((iChar = bufferedReader.read()) != -1) {No difference, now the application hangs at read() instead of readline()
    - tried to call handle via
    runtime = Runtime.getRuntime();               
    Process p = runtime.exec("C:\\tmp\\Handle\\handle C:\\tmp\\foo.txt");and
    Process process = runtime.exec( "cmd", "/c","C:\\tmp\\Handle\\handle.exe C:\\tmp\\foo.txt");No difference.
    - i thought that maybe for security reasons tomcat wont execute external programs, but a "nslookup www.google.de" within the application is executed
    - The file permissions on handle.exe seem to be correct. The user under which tomcat runs is NT-AUTORIT-T/SYSTEM. If i take a look at handle.exe permission i notice that user "SYSTEM" has full access to the file
    - I dont start tomcat with the "-security" option
    - Confusingly enough, the same code works under linux with "lsof", so this does not seem to be a tomcat problem at all
    Thx for any help!

    Hi,
    thx for the links, unfortanutely nothing worked........
    What i tried:
    1. Reading input and errorstream separately via a thread class called streamgobbler(from the link):
              String pathToFileHandleTool = "C:\\tmp\\Handle\\handle.exe";
              String pathToFile = "C:\\tmp\\foo.txt";
              String expectedFileHandleSuccessOutput = "(.*)No matching handles found(.*)";
              logger.debug("pathToFileHandleTool: " + pathToFileHandleTool);
              logger.debug("pathToFile: " + pathToFile);
              logger.debug("expectedFileHandleSuccessOutput: " + expectedFileHandleSuccessOutput);
              ProcessBuilder builder = new ProcessBuilder( pathToFileHandleTool, pathToFile);
              String commandOutput = "";
              try {
                   logger.debug("trying to start builder....");
                   Process process = builder.start();
                   logger.debug("builder started!");
                   logger.debug("trying to initialize error stream gobbler....");
                   StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
                   logger.debug("error stream gobbler initialized!");
                   logger.debug("trying to initialize output stream gobbler....");
                   StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT");
                   logger.debug("output stream gobbler initialized!");
                   logger.debug("trying to start error stream gobbler....");
                   errorGobbler.start();
                   logger.debug("error stream gobbler started!");
                   logger.debug("trying to start output stream gobbler....");
                   outputGobbler.start();
                   logger.debug("output stream gobbler started!");
                   // wait till process has finished
                   logger.debug("waiting for process to exit....");
                   int exitVal = process.waitFor();
                   logger.debug("process terminated!");
                   logger.debug("exit value: " + exitVal);
              } catch (IOException e) {
                   logger.debug(e.getMessage());
                   logger.debug(e);
              }  catch (InterruptedException e) {
                   logger.debug(e.getMessage());
                   logger.debug(e);
         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;
                     logger.debug("trying to call readline() .....");
                     while ( (line = br.readline()) != null)
                         logger.debug(type + ">" + line);   
                 } catch (IOException ioe) {
                         ioe.printStackTrace(); 
         }Again, the application hangs at the "readline()":
    pathToFileHandleTool: C:\tmp\Handle\handle.exe
    pathToFile: C:\tmp\openSUSE-10.2-GM-i386-CD3.iso
    expectedFileHandleSuccessOutput: (.*)No matching handles found(.*)
    trying to start builder....
    builder started!
    trying to initialize error stream gobbler....
    error stream gobbler initialized!
    trying to initialize output stream gobbler....
    output stream gobbler initialized!
    trying to start error stream gobbler....
    error stream gobbler started!
    trying to start output stream gobbler....
    output stream gobbler started!
    waiting for process to exit....
    trying to call readline().....
    trying to call readline().....Then i tried read(), i.e.:
         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);
                     logger.debug("trying to read in single chars.....");
                     int iChar = 0;
                     while ( (iChar = br.read()) != -1)
                         logger.debug(type + ">" + iChar);   
                 } catch (IOException ioe) {
                         ioe.printStackTrace(); 
         }Same result, application hangs at read()......
    Then i tried a dirty workaround, but even that didnt suceed:
    I wrote a simple batch-file:
    C:\tmp\Handle\handle.exe C:\tmp\foo.txt > C:\tmp\handle_output.txtand tried to start it within my application with a simple:
    Runtime.getRuntime().exec("C:\\tmp\\call_handle.bat");No process, no reading any streams, no whatever.....
    Result:
    A file C:\tmp\handle_output.txt exists but it is empty..........
    Any more ideas?

  • Process.waitFor returns early

    I'm launching a process which I then wait for with Process.waitFor(). I have the necessary IO reader threads in place to prevent buffer overflows.
    However, the waitFor is returning early. I can see that after returning the process is still running in the Windows task manager.
    What could be happening here? I'm using Eclipse under Windows XP Pro - which seems to run a special JVM javaw.exe.

    Thanks for the reply. Seems to be my mistake, the subprocess I'm calling, launches another background process over the same executable then returns - so it looks like the first process is still running, when infact it is not.

  • Process.waitFor doesn't waitFor process to terminated

    I have searched this website and found may people have this problem, but no one has answer the question. Does that mean there is no way around this?
    This is from the API:
    The Runtime.exec methods may not work well for special processes on certain native platforms.
    Is this everyones problem?
    This is the code I'm using:
    String[] callAndArgs = {"open", fileLoc};
    proc = rt.exec(callAndArgs2);
    proc.waitFor();This doesn't waitFor the open file to be closed. How can I waitFor for the open file to be closed? Is there away around this? Any input would be greatly appreciated. Thank you.

    Yes - you are kind of out of luck. The OS is spawning a new process to open that document, so the thread that you initiate with exec is ending, causing control to return to the Java app's .waitFor call.
    Many OSes do have the ability to shell out a command and actually wait for the process to end, but you'd have to invoke a native (JNI) method to do this. For example, I know you can do this with Windows by obtaining the process ID from the ShellExecute command and then performaing a wait on the process ID.
    At this point, though, you are out of the realm of Java programming.
    - K

  • Process.waitFor() error

    I am trying to run another java program from within a Servlet. Part of what I need to do is time it incase there is an endless loop, etc. My problem is this:
    When I execute the program, using Runtime-exec(...), and feed it more than 20 arguments, it runs perfectly fine without Proc.waitFor(), when there are less than 21 arguments, it runs perfectly fine with proc.waitFor(), however, when there are more than 20 arguments, proc.waitFor hangs, and times out when there is an interrupted exception, generated by an "AlarmClock" class.
    here is some code:
                    Thread t = Thread.currentThread();
                    long interval = 10000; // 10 seconds
                    AlarmClock ac = new AlarmClock(t,interval);
                    Thread clock = new Thread(ac);
                    clock.start();
                    proc = rt.exec(command,null,new File(full_dir));
                    try {
                       proc.waitFor(); // <--this one hates me
                        clock.interrupt(); // stop the alarm clock
                    }catch (InterruptedException ie) {  // we timed out and were interrupted by the alarm clock       
                    proc.destroy();  // kill the process              
    }Where command is a String array = {java,-classpath,<path>,<main file>, arg0, arg1,....,argN-1,argN}
    if N > 20, then it hangs.
    And AlarmClock just generates an interupted exception at the given interval.

    I think I found the solution to my own Problem...
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    -Dave

  • Process.waitFor() causes program to hang!

    I've successfully created a Process and run it using Runtime's exec(String path), and the kinds of processes I've successfully run have included Winzip, a WS_FTP Pro script, and a regular .bat file. I've also successfully called waitFor() on these processes, but in this particular case I'm calling a program that takes a file I give it as a parameter and merges its data into a database. I've been doing this procedure for a while (either from a command line or in a .bat file), but now I need to call it from my Java code. Preferably I'd like to waitFor() the process each time because I need to make sure all the files are merged in chronological order. My current test case only uses ONE file, but in reality there will be several. With one file, I can run the program and it appears to run fine (and it runs fast--like maybe a second or two at most), but whenever I call the following line it hangs indefinitely (I've never seen it terminate, even after several minutes):
    focusProcess.waitFor();
    When I just execute that program by itself by calling a .bat file with a hardcoded filename, I get standard output back from the program I'm calling. I'd like to see this output when I run my Java program and it appears to run fine, because I have no way if it IS running correctly! So, I added the following:
    BufferedInputStream bis = new BufferedInputStream(focusProcess.getInputStream());
    StringBuffer sb = new StringBuffer();
    int c;
    while((c=bis.read()) != -1) {   
    sb.append(c);
    bis.close();
    I'm not sure if this is the right way to monitor that InputStream that I get from the process, and even if that InputStream is going to give me the standard output from that the process normally writes to the terminal. All I do know is that again, the program seems to hang indefinitely, and I guess it has to do with the fact that maybe this process isn't notifying me that it's terminated, and so I'm still waiting for the rest of that InputStream. And yes, I HAVE tried both of these situations together AND separately (so I know that both pieces of code cause the program to hang).
    Any ideas would be much appreciated!

    Paying attention to the standard output from the running process is good for debugging (and reporting program progression, if necessary) but probably doesn't contribute to the problem you are seeing. The standard input to the process, however, is a different story. If the process you have Runtime.exec'd is waiting for something on stdin, then the OS will block on behalf of the program that is blocking for input and never terminate!
    Try running the exec'd command from the command-line and see if it needs any input (i.e. you have to press a key, or enter, or send EOF) for the program to complete. If this is the case then your Java program must supply that process with the appropriate input or it will just hang.
    As for printing the output from a process... here's a quick proof of concept:
    import java.io.*;
    public class Exec {
        public static void main(String args[]) throws Exception {
            // Make sure we've got something to exec.
            if ( args == null || args.length < 1 ) {
                System.out.println("Usage: java Exec COMMAND [ARGS...]");
                System.exit(1);
            // Run the process and print the output.
            Process p = Runtime.getRuntime().exec(args);
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ( (line=in.readLine()) != null ) {
                System.out.println("EXEC: "+line);
    }Hope this helps!
    -mike

  • Process.waitfor seems to wait indefinately

    Hello I'm running the folowing code from Java:
    Runtime run = Runtime.getRuntime();
    Process proc = run.exec(cmd);
    proc.waitFor();
    I've used this piece of code before in other programs and never had any problems with it.
    Now, however, the program hangs when it reaches the proc.waitfor line. So it seems my programm is never notified that the external command I'm executing has finished.
    DOes anyone have any experience with this sort of problem?
    Mark

    Ok, I read it and most if not all I considered already.
    The strange thing is, I'm doing a content conversion via FFMpeg followed by flvtool2 to add header info to my flash files.
    For small files all is well, and the program runs without problems. But when I try to convert a large file, which results in a large (aprox. 10Mb) flash video, the application hangs when I run the external program flvtool2. This only happens when processing large flash files though. With small flash files, there's no problem.
    Mark

  • How can I make Process.waitFor() just wait for a limited period?

    For example,
    Process prc=Runtime.getRuntime().exec(cmd);
    prc.waitFor(some seconds);
    if(prc.exitValue() != 0){
    // the subprocess hadn't terminated normally in some seconds,
    // so just forcilly kill it.
    prc.destroy();
    Is there any way to do this?

    waitFor does not have a timeout parameter, but you can start a Timer or thread to interrupt your waiting thread when the timeout expires. Then, waitFor will end, throwing an InterruptedException that you can catch.

  • What does  waitFor() in process returns    --Urgent

    Hi all
    i am calling an exe from browser on solaris, i am able to execute a normal exe file from browser
    but my exe is linked with other libraries and this exe is not executing from browser.
    when i use waitFor() i am getting 9 and 3 numbers.
    can any one tell me what these numbers mean?
         p=r.exec("/data/disk1/edss.exe");
         p=r.exec(commands);
    int v=p.waitFor();
         out.println("ret="+v);
         BufferedReader reader =     new BufferedReader(new InputStreamReader(p.getInputStream()));
         while((s = reader.readLine())!=null){
         System.out.println(s);
    ret=3 and sometimes 9.
    any one kindly provide solution?
    Thanks
    bye

    Quoting from the SDK documentation for Process.waitFor():
    the exit value of the process. By convention, 0 indicates normal termination
    so the vaues are the exit values for the program you executed, edss.exe

  • Can I poll an external process to see when it completes?

    New to Java programming, I need to kick off an external program and want to monitor it to determine when it terminates. Is this doable using Process class? I'm using Process process = Runtime.getRuntime().exec(cmd); The method calls for Process did not look promising and process.waitFor(); is a blocking call which can cause the program to hang if enough output is not routinely read in.
    Thank you for any suggestions.
    Ronald

    Ronald_Tutone wrote:
    New to Java programming, I need to kick off an external program and want to monitor it to determine when it terminates. Is this doable using Process class? I'm using Process process = Runtime.getRuntime().exec(cmd); The method calls for Process did not look promising and process.waitFor(); is a blocking call which can cause the program to hang if enough output is not routinely read in.
    Thank you for any suggestions.
    RonaldRegarding the blocking call and hang possibility, you need to read this article and implement what it suggests:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Why the Process is still in deadlock when i have exhaust its error stream.

    There is the code:
    import java.io.*;
    public class ProcessExec {
      public static void main(String[] args) {
         * Test the Process created by Runtime.exec().
        Runtime rt = Runtime.getRuntime();
        String s = new String();
        if(args.length < 1) {
          System.out.println("Usage: java ProcessExec executionName");
          System.exit(-2);
        try {
          Process process = rt.exec(args[0]);
           * Buffer the error stream and exhaust it.
          System.out.println("ErrorStream data of Porcess:");
          BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
          while( (s = br.readLine()) != null) {
            System.out.println(s);
          System.out.println("\n\n------------------------------------------------------------\n\n");
           * Buffer the input stream and exhaust it.
          br = new BufferedReader(new InputStreamReader(process.getInputStream()));
          System.out.println("InputStream data of Porcess:");
          while( (s = br.readLine()) != null) {
            System.out.println(s);
          System.out.println("Return num: " + process.waitFor());
        catch(Throwable t) {
          System.out.println(t);
    }When i run the "javac" as :
    C:\classses\lang\java ProcessExec javac
    The process run correctly and print the error stream.
    But when i run the "java" as:
    C:\classes\lang\java ProcessExec java
    The process was in deadlock?
    Why,in my code i have buffered the error stream and input stream using a BufferedReader and then exhausted them.
    And when i invoke the "javac" it ran correctly but why it couldnt run correctly when i invoked the "java" execution?

    A deadlock occurs when two locks are dependant on each other.
    This is unlikely to be the case here.
    With out your exact command line or what your output is or if you have a dealock we will need to see the thread dump which displays where the deadlock is.

  • What is the best practice dealing with process.getErrorStream()

    I've been playing around creating Process objects with ProcessBuilder. I can use getErrorStream() and getOutputStream() to read the output from the process, but it seems I have to do this on another thread. If I simply call process.waitFor() and then try to read the streams that doesn't work. So I do something like final InputStream errorStream = process.getErrorStream();
    final StringWriter errWriter = new StringWriter();
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(
        new Runnable() {
            public void run() {
                try {
                    IOUtils.copy(errorStream, errWriter, "UTF-8");
             } catch (IOException e) {
                    getLog().error(e.getMessage(), e);
    int exitValue = process.waitFor();
    getLog().info("exitValue = " + exitValue);
    getLog().info("errString =\n" + errWriter); This works, but it seems rather inelegant somehow.
    The basic problem is that the Runnable never completes on its own. Through experimentation, I believe that when the process is actually done, errorStream is never closed, or never gets an end-of-file. My current code works because when it goes to read errWriter it just reads what is currently in the buffer. However, if I wanted to clean things up and use executorService.submit() to submit a Callable and get back a Future, then a lot more code is needed because "IOUtils.copy(errorStream, errWriter, "UTF-8");" never terminates.
    Am I misunderstanding something, or is process.getErrorStream() just a crappy API?
    What do other people do when they want to get the error and output results from running a process?
    Edited by: Eric Kolotyluk on Aug 16, 2012 5:26 PM

    OK, I found a better solution.Future<String> errString = executorService.submit(
        new Callable<String>() {
            public String call() throws Exception {
                StringWriter errWriter = new StringWriter();
                IOUtil.copy(process.getErrorStream(), errWriter, "UTF-8");
                return errWriter.toString();
    int exitValue = process.waitFor();
    getLog().info("exitValue = " + exitValue);
    try {
        getLog().info("errString =\n" + errString.get());
    } catch (ExecutionException e) {
        throw new MojoExecutionException("proxygen: ExecutionException");
    } The problem I was having before seemed to be that the call to Apache's IOUtil.copy(errorStream, errWriter, "UTF-8"); was not working right, it did not seem to be terminating on EOS. But now it seems to be working fine, so I must have been chasing some other problem (or non-problem).
    So, it does seem the best thing to do is read the error and output streams from the process on their own daemon threads, and then call process.waitFor(). The ExecutorService API makes this easy, and using a Callable to return a future value does the right thing. Also, Callable is a little nicer as the call method can throw an Exception, so my code does not need to worry about that (and the readability is better).
    Thanks for helping to clarify my thoughts and finding a good solution :-)
    Now, it would be really nice if the Process API had a method like process.getFutureErrorString() which does what my code does.
    Cheers, Eric

  • Spawned process blocks grand parent

    I ran into a problem on Windows with a chain of processes where the top Java process would not exit until the bottom non-Java process exited, even though intermediate Java or Non-java processes had exited. For example: the top Java process spawns a Java subprocess and communicate with it through standard IO streams. That subprocess then spawns a detached non-Java subsubprocess and returns. The problem is that even though the subprocess had exited, the parent process blocked until the subsubprocess exited.
    I tracked down the source of the problem to Java executing all sub processes with the "bInheritHandles" flag for the CreateProcess API set to TRUE, while it should be set to FALSE for detached processes.
    Are there any plan for Java to provide an API to create fully detached processes under Windows?
    Georges
    I reduced the problem to this code:
    Here is the top level script that demonstrate the problem:
    @ECHO OFF
    SETLOCAL & PUSHD %~dp0
    SET JDK_HOME=c:\Program Files\Java\jdk1.6.0
    SET JDK_HOME=c:\j2sdk1.4.2_09
    "%JDK_HOME%\bin\javac" *.java
    ECHO This shows the problem with child Java subprocess that
    ECHO spawns Notepad subsubprocess:
    "%JDK_HOME%\bin\java" -classpath . Exec1
    ECHO Parent Java process exits when Notepad subsubprocess exits.
    POPD & ENDLOCALThis is the parent Java process that spawns a Java subprocess and gets status from it: Exec1.java:
    class Exec1 {
        private static Thread streamOutputThread;
        private static Thread streamErrorThread;
        public static void main(String[] args) {
            try {
                Process process = Runtime.getRuntime().exec("Exec2.bat");
                streamOutputThread = new Thread(new StreamReader(process
                        .getInputStream()));
                streamOutputThread.setDaemon(true);
                streamErrorThread = new Thread(new StreamReader(process
                        .getErrorStream()));
                streamErrorThread.setDaemon(true);
                streamOutputThread.start();
                streamErrorThread.start();
                process.waitFor();
                streamOutputThread.join();
                streamErrorThread.join();
            } catch (Exception ex) {
                ex.printStackTrace();
                return;
    }This is the class that handle the communication: StreamReader.java.
    import java.io.InputStream;
    public class StreamReader implements Runnable {
        private static final int SIZE = 128;
        private InputStream is;
        public StreamReader(InputStream is) {
            this.is = is;
        public void run() {
            final byte[] buf = new byte[SIZE];
            int length;
            try {
                while ((length = is.read(buf)) > 0) {
                    System.out.write(buf, 0, length);
            } catch (Exception e) {
                // ignore errors
    }This is the intermediate script that show that the Java subprocess has exited: Exec2.bat
    @ECHO OFF
    SETLOCAL & PUSHD %~dp0
    SET JDK_HOME=c:\Program Files\Java\jdk1.6.0
    SET JDK_HOME=c:\j2sdk1.4.2_09
    "%JDK_HOME%\bin\java" -classpath . Exec2
    POPD & ENDLOCAL
    ECHO Child Java subprocess exited.
    ECHO Parent Java process still waiting for spawned Notepad subsubprocess to exit!!!!!This is the Java subprocess that spans the Notepad subsubprocess: Exec2.java.
    class Exec2 {
        public static void main(String[] args) {
            try {
                System.out.println(
                    "Child java subprocess spawning Notepad subsubprocess...");
                Runtime.getRuntime().exec("Notepad");
            } catch (Exception ex) {
                ex.printStackTrace();
                return;
    }

    It would be helpful if you posted a question!

Maybe you are looking for

  • Adding a PC to my wireless network

    I would like to find out how I can add a Windows laptop (as yet unpurchased, so assume your basic Dell, Lenovo, HP, etc. running Windows 7) to my wireless network. I currently have an iMac running 10.6.5 and an Airport Extreme Base Station. I would l

  • Word VBA Macro problem with adding rows to table for BAPI call

    Hello all, I have code in Word macro which is reading file from the disk and converting it to binary. This binary should be inserted in the internal table (Dim As object) for further posting. Code is modified from the note 945682. Here is the code: S

  • 1.67GHz G4 15-inch Battery

    Just opened 2 brand new powerbooks and neither of them will charge. The reading is at 0% and the light is green. tried resetting the power management unit. No change. ANything else I could try/do? Thanks in advance.

  • Setting work item as obsolete

    Hi Experts, We are using modeled deadline monitoring. We are setting the " Workitem to obsolete" in the process control step. Does this imply that the approver will not be able to execute the work item once it crosses it deadline. In case of repeated

  • HT5312 I need to rescue my security questions, how I do it?

    Hi, I forgot my security questions, how the rescue?