Question about Runtime.exec

Rob,
Thanks for your help.
I asked a question about a weird Exception on Nov 14, and you told me that I am
using Runtime.exec to start an external process, and that process is crashing.
I am a green-hand on Weblogic, and I am trying to enhancing a project developped
by another person, so I am not familiar with some concepts yet.
Could you please give me some simple explanation about Runtime.exec and external
process?
I found two methods that uses "Runtime" from two classes as following, could you
help me to see whether or not there is something wrong with the usage of Runtime?
Thank you very much.
private int runShellCommand(String command) {
int exitVal = -1;
try {
File runDir = new File(runDirectory);
String[] env = new String[0];
Runtime rt = Runtime.getRuntime();
               double start = System.currentTimeMillis();
Process proc = rt.exec(command, env, runDir);
// Capture output in separate thread
ThreadedStreamReader error = new ThreadedStreamReader(proc.getErrorStream(),
"ERROR");
ThreadedStreamReader output = new ThreadedStreamReader(proc.getInputStream(),
"OUTPUT");
error.start();
output.start();
exitVal = proc.waitFor();
if (logger.isDebugEnabled()) {
     double runtime = (System.currentTimeMillis() - start) / 1000.0;
     logger.info("run " + runId + " " + command + " finished in " + runtime
+ " seconds");
} catch (IOException e) {
logger.fatal("DOE-2 failed \n" + e.getMessage());
} catch (InterruptedException e) {
e.printStackTrace();
return exitVal;
public static void main(String[] args) throws Exception, InterruptedException
final Doe2MessageServer server = new Doe2MessageServer();
while(!connected) {
Thread.sleep(1000);
logger.info("Attempting to start JMS service ...");
               try {
          server.init();
               } catch (Exception ex) {
// shutdown hook to close JMS connection
Runtime.getRuntime().addShutdownHook(
new Thread() {
public void run() {
server.finalize();
server.receiveMessage();

Runtime.exec is a J2SE API. It's not really specific to WLS.
You can read about it here:
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Runtime.html
It looks like you are starting a JMS Server in a separate process and
that process is crashing.
(You could of course just use WLS's JMS Server instead :>)
-- Rob
Iris Qu wrote:
Rob,
Thanks for your help.
I asked a question about a weird Exception on Nov 14, and you told me that I am
using Runtime.exec to start an external process, and that process is crashing.
I am a green-hand on Weblogic, and I am trying to enhancing a project developped
by another person, so I am not familiar with some concepts yet.
Could you please give me some simple explanation about Runtime.exec and external
process?
I found two methods that uses "Runtime" from two classes as following, could you
help me to see whether or not there is something wrong with the usage of Runtime?
Thank you very much.
private int runShellCommand(String command) {
int exitVal = -1;
try {
File runDir = new File(runDirectory);
String[] env = new String[0];
Runtime rt = Runtime.getRuntime();
               double start = System.currentTimeMillis();
Process proc = rt.exec(command, env, runDir);
// Capture output in separate thread
ThreadedStreamReader error = new ThreadedStreamReader(proc.getErrorStream(),
"ERROR");
ThreadedStreamReader output = new ThreadedStreamReader(proc.getInputStream(),
"OUTPUT");
error.start();
output.start();
exitVal = proc.waitFor();
if (logger.isDebugEnabled()) {
     double runtime = (System.currentTimeMillis() - start) / 1000.0;
     logger.info("run " + runId + " " + command + " finished in " + runtime
+ " seconds");
} catch (IOException e) {
logger.fatal("DOE-2 failed \n" + e.getMessage());
} catch (InterruptedException e) {
e.printStackTrace();
return exitVal;
public static void main(String[] args) throws Exception, InterruptedException
final Doe2MessageServer server = new Doe2MessageServer();
while(!connected) {
Thread.sleep(1000);
logger.info("Attempting to start JMS service ...");
               try {
          server.init();
               } catch (Exception ex) {
// shutdown hook to close JMS connection
Runtime.getRuntime().addShutdownHook(
new Thread() {
public void run() {
server.finalize();
server.receiveMessage();

Similar Messages

  • Need info about Runtime.exec

    Hello, I have a non program specific question about how Runtime.exec works. First off assume that I handle all my input streams and output streams correctly, and I am not worried about inter process communication. The question is, when I use Runtime.getRuntime().exec(cmd[],pth[],dir) does the JVM that is running the code that calls it live until the spawned process dies, or can it die without waiting for the execed process to die? I am trying to write an app that can spawn a new copy of itself that is completely independent from the original process, and may live on long after the original is no longer needed. To ensure proper resource management I need to know that the JVM that launches the new process does not have to wait for the new process to die prior to completely cleaning itself up.
    Does that make sense?
    Any suggestions, ideas, questions?
    Thanks in advance for the help.
    Message was edited by:
    elixic

    Thank you all who gave useful input. I had done some reading on this already and could not find a definite answer on weather or not the calling JVM can properly dispose of itself prior to the process it called being disposed of.
    The answer it seems is dependent on context. In windows, and from a GUI app, it looks like the calling JVM can die any time it wants too. A command line app on the other hand seems to have to wait for the app it called to die first. I have not tested it on other OS's but I am sure it varies by OS as well. I would not even be surprised if it varies by JVM.
    So the short answer to my question that you all helped me find is this, It varies by context.
    Thanks again for the help.
    Isaac

  • Questions on Runtime.exec

    Currently i need to backup a file from the current directory to a Archive directory. So to rename the file in the current directory then move it or copy it into the Archive directory.
    My question is can Runtime.exec () run 2 commands
    first will be "cmd /c start rename A*.zip A_01.zip"
    second will be "cmd /c copy A_01.zip newfolder\A_01.zip" ?
    Reason why i dun wan to run 2 .exec() statement is that i dun wan too many popout screens.
    Hope I can get my solution here.
    Thanks

    don't know whether it works on windoze too, but on unix you can execute several commands seperated by an ";". perhaps this works for exec() too (?)
    so far,
    stefan g.

  • Very very urgent! Please help about Runtime.exec on Solaris

    I wrote a software in Java.
    It contains a platform application and a variety of client applicaitons.
    Both use Swing MMI. I need my own JRE and invoke client from
    platform MMI. On Windows, the software run ok. But on Solaris,
    client are always blocked to do work.
    Whe run platform and client individually from command line,
    client will run ok too. While client is invoked by platform in programm,
    it will be blocked to run (client cannot recieve data from RS232).
    I noticed that client will continue to run once platform exits.
    So I really wonder whether there is something wrong with my codes
    to invoke client. Only Solaris invoking codes list here.
      public static boolean exec(String execStr) {
        Runtime runtime = Runtime.getRuntime();
        try {
          String[] args  = new String[] {
                "/bin/sh", "-c", execStr};
            Process p = runtime.exec(args);
            return true;
          return false;
         catch (Exception e) {
          e.printStackTrace();
        return false;
      }

    The execStr argment is
    /users/devConfig/jre/java -classpath "/users/devConfig/jre/lib:/users/devConfig/lib/ssop.jar:
    /users/devConfig/lib/zt103.jar..." zt.client.nsd200v.NSD200VApp ...Where /users/devConfig is my software installed directory, and /users/devConfig/jre is my own packaged JRE1.5.0.

  • How to make this works. it's about Runtime.exec().

    hi' i really need help about this.
    i have 2 class file. one named GoodWindowsExec that used to execute another file named maintest. (i post my code below). When i run GoodWindowsExec there's no problem but not working correctly.
    What i need is i can write something directly from my keyboard not via GoodWindowsExec file. So maintest can run normally just like when i execute it manual (java maintest from commandprompt) and display the output. If you look at the maintest file, this file need input from user. But why i can't doing this directly? How to implement this?
    This is java code that i need to execute (maintest) just for sample :
    public class maintest
         public static void main(String[] args)
              try
                   BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
                   System.out.print("Try input word : ");
                   String readInput = bfr.readLine();
                   /* String readInput = bfr.readLine(); i think this is the problem.
                    * If i remove this, GoodWindowsExec works fine.
                    * But i cannot remove it. This is my point.
                    * i want try to solve this */
                   System.out.println(readInput);
              catch(Exception e)
                   System.out.println(e);
    }This is my code (GoodWindowsExec) which used to execute maintest :
    public class GoodWindowsExec
         public GoodWindowsExec()
              try
                   String[] cmd = new String[]{"cmd.exe","/C","java","maintest"};
                Runtime rt = Runtime.getRuntime();
                   Process proc = rt.exec(cmd);
                   InputStream inStream = proc.getInputStream();
                   BufferedReader bfr = new BufferedReader(new InputStreamReader(inStream));
                   response res_in = new response(bfr);
                   InputStream errorStream = proc.getErrorStream();
                   BufferedReader errorBfr = new BufferedReader(new InputStreamReader(errorStream));
                   response res_err = new response(errorBfr);
                   res_in.start();
                   res_err.start();
                   OutputStream otStream = proc.getOutputStream();
                   DataOutputStream write = new DataOutputStream(otStream);
                   write.writeUTF("something");
                   /* write.writeUTF("something");
                    * i really don't know about this.
                    * if i declare this, the input not come from maintest / user directly.
                    * if i create some java editor application and want to execute some java code
                    * this is not right. cos input comes from this class not the execute class (maintest).
                    * How to make the input comes from user / execute class?
                   write.flush();
                   write.close();
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
              catch (Throwable t)
                 t.printStackTrace();
        public static void main(String args[])
              new GoodWindowsExec();
    class response extends Thread
         BufferedReader bfr;
         public response(BufferedReader bfr)
              this.bfr = bfr;
         public void run()
              try
                   String line = null;
                   while ( (line = bfr.readLine()) != null)
                             System.out.println(line);   
              catch (IOException ioe)
               ioe.printStackTrace(); 
    }Thank you very much...

    Hi' i think i have same problems with you. but now i think i got it after read this article. Thanks for both of you. specially sabre150.
    But i want to ask about this to sabre150. What if maintest try to request more than one input? How to handle it? and why Try input word : display at the second line? not the first line?
    i'm sorry if i modify this, but i change it like this :
    class outputer :
    public void run()
         try
              bfr = new BufferedReader(new InputStreamReader(System.in));
              String input = null;
              while ((input = bfr.readLine()) != null)
                   write.writeBytes(input);     
                   write.flush();
                   write.close();
         catch(Exception e)
              e.printStackTrace();
    }maintest :
    public class maintest
         public static void main(String[] args)
              try
                   BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
                   System.out.print("Try input word : ");
                   String readInput = bfr.readLine();
                   System.out.println(readInput);
                   System.out.print("Try input word again : ");
                   String readInput2 = bfr.readLine();
                   System.out.println(readInput2);
              catch(Exception e)
                   System.out.println(e);
    }When i execute i got this :
    test //request for first input
    Try input word : test
    Try input word again : null
    ExitValue: 0
    halo //request for second input
    java.io.IOException: The handle is invalid
         at java.io.FileOutputStream.writeBytes(Native Method)
         at java.io.FileOutputStream.write(Unknown Source)
         at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
         at java.io.BufferedOutputStream.flush(Unknown Source)
         at java.io.DataOutputStream.flush(Unknown Source)
         at outputer.run(GoodWindowsExec.java:78)Maybe you know the answer sabre150?
    Thanks...
    Message was edited by:
    2Puluh11Lapan3

  • About runtime.exec("passwd")

    In solaris,you can use command "passwd" to change password of user.
    Now i want to use the command in java.But i can not get the result like below:
    %new password:(type the password)
    Re-type password:
    my codes is copied here,please help me .
    import java.util.Enumeration;
    import java.io.*;
    import java.lang.*;
    public class liu{
         public static void main(String args[]) throws Exception{
              try{
                   Runtime rr=Runtime.getRuntime();
                   String[] aaa={ "passwd"};//passwd liuyang"};//ls -l"};
                   Process cess=rr.exec(aaa);
              String sss;
                   DataOutputStream out=new DataOutputStream(new BufferedOutputStream(cess.getOutputStream()));
    //               out.writeBytes("qwerty\n");
                   out.writeBytes("OUTPUT");
                   out.flush();
                   DataInputStream in=new DataInputStream(cess.getInputStream());
                   while((sss=in.readLine())!=null)
                        System.out.println(sss);
              }catch (Exception ex) {
                   System.out.println("Exception:"+ex);

    I would really recommend not to code your own password utility in java. Yours will be insecure and will echo onto the screen whilst the default unix one will be as secure as sun can make it.
    Jon

  • About runtime.exec()

    hi friends,
    i'm unable to open vb exe file through java application.
    i'm tring with this code
    Process p = Runtime.getRuntime().exec("cmd /D:Program Files/Microsoft Visual Studio/VB98/socketappvb/");
    p.waitfor()
    that is the error in my code.
    thank is advance

    Your exec string doesn't look right. What the heck are those forward slashes? And why do you call cmd for an exe? (Can't say for sure, but I believe the cmd is only required to execute batch files.)

  • Help me ! about Runtime.exec()

    [php]
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.File;
         /** * Class for running external executable (extrnal process).*/
    public class ExeRunner{     
    /* Path to Dlls required by the executable */
    String path = "C:\\Program Files\\jdk1.4\\bin";
    public void run(String [] args) throws IOException, InterruptedException
    final Process p = Runtime.getRuntime().exec(args, new String [] {path});
    new Thread()
    public void run()
    try
    BufferedReader in = new BufferedReader (new InputStreamReader (p.getInputStream()));     
    String str = null;     
    while ((str = in.readLine()) != null )     
    System.out.println(str);     
    in.close();     
    catch (IOException e){      
    e.printStackTrace();     
    }.start();
    new Thread()
    public void run()
    try     {     
    BufferedReader in      = new BufferedReader (new InputStreamReader (p.getErrorStream()));     
    String str = null;     
    while ( (str = in.readLine()) != null )
    System.err.println(str);
    in.close();     
    catch (IOException e)
    {       e.printStackTrace();
    }.start();
    int exitCode = p.waitFor();          
    if ( exitCode != 0 )
    throw new IOException ("Executable "+args[0]+" stopped with error code "+exitCode);
    public static void main(String [] a) throws Exception
    String args [] = new String[4];
    args[0] = "C:\\Program Files\\jdk1.4\\bin\\java.exe";
    args[1] = "-classpath";
    args[2] ="E:\\Practical";
    args[3] ="HelloWorld";
    new ExeRunner().run(args);
    [php]

    I get the above from another forum. the program running well.
    however , my problem is that I want to it display another DOS console to print the "Hello World ".
    and the DOS console will not closed untill user close it.
    /* Path to Dlls required by the executable */
    String path = "C:\\Program Files\\jdk1.4\\bin";
    final Process p = Runtime.getRuntime().exec(args, new String [] {path});
    can you explain what the above line doing. and what is the "path" means?
    I also tried to change the codes in main method
    String args [] = new String[6];
    args[0] ="cmd.exe";
    args[1] ="/start";
    args[2] = "C:\\Program Files\\jdk1.4\\bin\\java.exe";
    args[3] = "-classpath";
    args[4] ="E:\\Practical";
    args[5] ="HelloWorld";
    new ExeRunner().run(args);
    But it does not work.
    Thanks very much!

  • Question About Runtime Class Not Found Exception

    Good Morning!
    I have a very simple test class that I am using to debug a class loader issue with log4j. I can compile my class. I put the class in a jar file with a manifest that points to the class with the main method. The log4j .jar file is in the .\lib directory, below the test1.jar file. I have fussed around with different variations of -cp & -classpath, without success. I can not figure out why the runtime environment can not load the org.apache.log4j.Logger class.
    What is wrong with the way that I am setting up the runtime environment?
    Thank you!
    ==========================
    source:
    import org.apache.log4j.Logger;
    public class Test1 {
        static Logger logger = Logger.getLogger(Test1.class);
        public static void main(String[] args) {
            System.out.println("Hello World");
    }===========================
    compilation:
    X:\test>javac -classpath .\;.\lib\log4j-1.2.14.jar Test1.java
    jar:
    X:\test>jar -cvmf .\META-INF\MANIFEST.MF test1.jar .\*.class
    added manifest
    adding: Test1.class(in = 627) (out= 380)(deflated 39%)
    MANIFEST.MF:
    Manifest-Version: 1.0
    Created-By: 1.5.0_11 (Sun Microsystems Inc.)
    Main-Class: Test1
    ==========================
    .\lib:
    X:\test>dir .\lib
    Volume in drive X is Storage
    Volume Serial Number is 5871-E6FF
    Directory of X:\test\lib
    11/25/2009 10:19 PM <DIR> .
    11/25/2009 10:19 PM <DIR> ..
    11/25/2009 10:05 AM 367,444 log4j-1.2.14.jar
    1 File(s) 367,444 bytes
    2 Dir(s) 27,042,570,240 bytes free
    X:\test>
    run:
    X:\test>java -client -classpath .\;.\lib\log4j-1.2.14.jar -jar test1.jar
    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/Logger
    at Test1.<clinit>(Test1.java:6)
    Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Logger
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    ... 1 more
    Could not find the main class: Test1. Program will exit.
    X:\test>

    Fussing around with the -classpath parameters won't do anything, because they are ignored when the -jar parameter is present. Running an executable jar means that you specified the classpath in the jar's manifest. Which you didn't do. You need a Class-Path entry in the manifest which provides the path to the log4j.jar file relative to your executable jar.

  • Problem executing file through Runtime.exec

    Hi,
    i am trying to execute a java programem using the the following line
    Runtime.exec("java Myclass");
    But no response for it.
    Anybody help me.
    Jossy

    As required by forum protocol for people who ask questions about Runtime.exec I am posting the standard link:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Question about using Runtime.getRuntime();

    hi all
    i have a question about using Runtime.getRuntime(). if i use this to get a runtime reference to run an external program, is it considered as starting a new thread inside the thread that starts it?
    is it safe to do it in the Session EJB? if not, what can you recommand to do it? thanks

    hi all
    i have a question about using Runtime.getRuntime().
    if i use this to get a runtime reference to run an
    external program, is it considered as starting a new
    thread inside the thread that starts it? No. Starting a process, starts a process. Threads have nothing to do with it.
    is it safe to do it in the Session EJB? if not, what
    can you recommand to do it? thanksSo what? Run another process? If you want to run another process in java then your choices are to use Runtime.exec() or use JNI. And using JNI will probably end up doing exactly the same thing as Runtime.exec().
    "Safe" is harder. Typically to correctly use Runtime.exec() you must use threads. And as noted threads ideally should not be used. You can use them but if you do you had better understand why they didn't want you using them in the first place. You had also better be sure that you really want to wait for it to complete.
    Other than that Runtime.exec() is safe because it can't crash the VM like other interfaces can (like JNI.)

  • Three questions about Java and Ftp

    Hello, i've the following questions about Java and Ftp:
    1- .netrc file is in $HOME directory but i can't access to this directory from java code. The following line producesan Exception (directory doesn't exists)
    FileWriter file = new FileWriter ("$HOME/.netrc");
    2- .netrc file must have the following permissions: -rw- --- --- but when i create the .netrc file the following permissions are on default: -rw- r-- r--, how can i change this permissions? (In java code, i can't use chmod.....)
    3- Are there any way to pass parameters to a .netrc file? If i get to do this i needn't change the permissions because i can't modify or create/destroy this file.
    Thanks in advanced!!!
    Kike

    1- .netrc file is in $HOME directory but i can't
    access to this directory from java code. The
    following line producesan Exception (directory
    doesn't exists)
    FileWriter file = new FileWriter ("$HOME/.netrc");$HOME would have to be replaced by a shell, I don't
    think you can use it as part of a legal path.
    Instead, use System.getProperty("user.home");
    Ok, thanks
    2- .netrc file must have the followingpermissions:
    -rw- --- --- but when i create the .netrc file the
    following permissions are on default: -rw- r--r--,
    how can i change this permissions? (In java code,i
    can't use chmod.....)Yes, you can: Runtime.exec("chmod ...");
    I need to use estrictly the .netrc with -rw- --- --- permissions
    Yes, i can use Runtime.exec ("chmod ..."); but i don't like very much this solution because is a slow solution, am i right?
    3- Are there any way to pass parameters to a.netrc
    file? If i get to do this i needn't change the
    permissions because i can't modify orcreate/destroy
    this file.I don't think so. Why do you need the .netrc file in
    Java at all? Writing a GUI frontend?I want to use automatic ftp in a java program and FTP server, the files and path are not always the same, so i can:
    - modify .netrc (for me is the complex option)
    - destroy and create a new .netrc (is easier but i have permissions problem)
    - use .netrc with parameters but i haven't found any help about it
    Thanks for your prompt reply!!!!
    Kike

  • Running java process in a while loop using Runtime.exec() hangs on solaris

    I'm writting a multithreaded application in which I'll be starting multiple instances of "AppStartThread" class (given below). If I start only one instance of "AppStartThread", it is working fine. But if I start more than one instance of "AppStartThread", one of the threads hangs after some time (occasionaly). But other threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside another thread?. Here I'm executing the process in a while loop.
    2. Other thing i noticed is the Thread is hanging after completing the process ("java ExecuteProcess"). But the P.waitFor() is not coming out.
    3. Is it bcoz of the same problem as given in Bug ID : 4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock. "
    I'm running this on sun Solaris/java 1.2.2 standard edition. If any of you have experienced the same problem please help me out.
    Will the same problem can happen on java 1.2.2 enterprise edition.?
    class AppStartThread implements Runnable
    public void run()
    while(true)
    try
    Process P=Runtime.getRuntime().exec("java ExecuteProcess");
    P.waitFor();
    System.out.println("after executing application.");
    P.destroy();
    P = null;
    System.gc();
    catch(java.io.IOException io)
    System.out.println("Could not execute application - IOException " + io);
    catch(java.lang.InterruptedException ip)
    System.out.println("Could not execute application - InterruptedException" + ip);
    catch (Exception e)
    System.out.println("Could not execute application -" + e.getMessage());

    I'm writting a multithreaded application in which I'll
    be starting multiple instances of "AppStartThread"
    class (given below). If I start only one instance of
    "AppStartThread", it is working fine. But if I start
    more than one instance of "AppStartThread", one of the
    threads hangs after some time (occasionaly). But other
    threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside
    another thread?. Here I'm executing the process in a
    while loop.Of course this is OK, as your code is always being run by one thread or another. And no, it doesn't depend on which thread is starting threads.
    2. Other thing i noticed is the Thread is hanging
    after completing the process ("java ExecuteProcess").
    But the P.waitFor() is not coming out.This is a vital clue. Is the process started by the Runtime.exec() actually completing or does the ps command still show that it is running?
    3. Is it bcoz of the same problem as given in Bug ID :
    4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited
    ed buffer size for standard input and output streams,
    failure to promptly write the input stream or read the
    output stream of the subprocess may cause the
    subprocess to block, and even deadlock. "These two are really the same thing (4098442 is not really a bug due to the reasons explained in the doc). If the program that you are exec'ing produces very much output, it is possible that the buffers to stdout and stderr are filling preventing your program from continuing. On Windows platforms, this buffer size is quite small (hundreds of characters) while (if I recall) on Solaris it is somewhat larger. However, I have seent his behavior causing problem on Solaris 8 in my own systems.
    I once hit this problem when I was 'sure' that I was emitting no output due to an exception being thrown that I wasn't even aware of - the stack trace was more than enough to fill the output buffer and cause the deadlock.
    You have several options. One, you could replace the System.out and System.err with PrintStream's backed up by (ie. on top of) BufferedOutputStream's that have large buffers (multi-K) that in turn are backed up by the original out and err PrintStream's. You would use System.setErr() and System.setOut() very early (static initializer block) in the startup of your class. The problem is that you are still at the mercy of code that may call flush() on these streams. I suppose you could implement your own FilterOutputStream to eat any flush requests...
    Another solution if you just don't care about the output is to replace System.out and System.err with PrintStreams that write to /dev/nul. This is really easy and efficient.
    The other tried and true approach is to start two threads in the main process each time you start a process. These will simply consume anything that is emitted through the stdout and stderr pipes. These would die when the streams close (i.e. when the process exits). Not pretty, but it works. I'd be worried about the overhead of two additional threads per external process except that processes have such huge overhead (considering you are starting a JVM) that it just won't matter. And it's not like the CPU is going to get hit much.
    If you do this frequently in your program you might consider using a worker thread pool (see Doug Lea's Executor class) to avoid creating a lot of fairly short-lived threads. But this is probably over-optimizing.
    Chuck

  • Reading InputStream from Runtime.exec() and ffmpeg?

    I've got a lot of things going on here and I'm having trouble debugging. I'm working on a streaming music player, and the platform only handles MP3 natively. Specifically, the method that handles incoming requests has to return an InputStream for further processing upstream (out of my visibility).
    I'm trying to extend the music player to play AAC files with the extension ".m4a". To do this, my plan is to transcode from MP3 to AAC using Runtime.exec() and ffmpeg, and then return an InputStream that contains the MP3. This works fine if I use ffmpeg to transcode to a temp file, and then return a FileInputStream constructed from that temp file. But like I said, this is supposed to be a steaming music player, and the blocking for the ~30 seconds it takes to completely transcode to a file is too much of a delay.
    So what I'm trying to do is have ffmpeg transcode to stdout, and then use Process.getInputStream() to return the InputStream that contains ffmpeg's stdout while the transcoding is still going on. This doesn't work and I'm not sure why. (I'm fairly new to java, and this is the first time I've used Runtime.) My player just hangs there. I know Runtime is picky about exhausting the stdout and stderr streams, so I'm not sure if it's something related to that, or if I somehow need to buffer the stdout before returning it, or if I need to run something in a different thread, or if I'm just completely barking up the wrong tree.
    If anyone has any experience with something like this, or can point me at some code that implements something similar, I'd appreciate the help.
    Below a sample of the code in question. Also, for what it's worth, all of the console messages that I put in there are printing, but the music doesn't play.
       public InputStream getStream(String uri) throws IOException
                 System.out.println("Entering Factory.getStream()");
                  System.out.flush();
                File file = new File(URLDecoder.decode(uri, "UTF-8"));
                if (file.exists())
                     if(file.getPath().toLowerCase().endsWith(".mp3")) {
                            // This code for playing MP3 files works correctly
                          System.out.println("Playing MP3");
                          System.out.flush();
                          InputStream in = new FileInputStream(file);
                          return in;
                     else if(file.getPath().toLowerCase().endsWith(".m4a")){
                          System.out.println("Playing M4A");
                          System.out.flush();
                          // Create array for ffmpeg command line
                            // This command line transcodes to STDOUT
                          String[] command = { this.ffmpeg_path,
                                                             "-i", 
                                                             "input.m4a",
                                                             "-acodec",
                                                             "libmp3lame",
                                                             "-ac",
                                                             "2",
                                                             "-ab",
                                                             "256",
                                                             "-f",
                                                             "mp3",
                          // Begin transcoding with ffmpeg
                          System.out.println("Transcoding...");
                          System.out.flush();
                          Runtime runtime = Runtime.getRuntime();
                          Process ffmpeg = runtime.exec(command);
                          // Must exhaust error stream, or the application can become deadlocked.
                          System.out.println("Exhausting stderr...");
                          System.out.flush();
                          this.exhaustInputStream(ffmpeg.getErrorStream());
                          // Return ffmpeg's stdout as an input stream
                          System.out.println("Returning stdout...");
                          System.out.flush();
                          return ffmpeg.getInputStream();
                     else {
                          System.out.println("Unsupported Audio File");
                          System.out.flush();
                          return null;
                else
                    // We aren't requesting a file, so let the API handle the request upstream...
                    return super.getStream(uri);
         private void exhaustInputStream(final InputStream inputStream) {
                  // Since InputStream.read() blocks, exhast the stream in a separate thread
                  new Thread() {
                       public void run() {
                            try {
                                 while(inputStream.read() >= 0) {
                                      // Just throw the bytes away
                            catch(IOException e) {
                                 e.printStackTrace();
                  }.start();
             }

    Read this article
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Runtime.exec and exitValue

    hi all,
    i know about the miolion of topics about this object, but i've a question a little bit more specific.
    I have a part of my code that needs to launch external command . I want to save the output of these commands, but i have to minimize the number of thread spawned. In addtion, i cannot know the number of command launched, so the thread number will became an important factor to bound.
    At the same time i need to write something at the end of the output file, so i need to know when the process launched has terminated.
    What i did:
    //  main
    //  here create a thread for process control
    //   procControlThread
    public void launchCommand(String cmd, String file, long ID){
      Process p  = Runtime.exec(cmd+" 1 >> "+file);
       procControlThread.addObj(p,file).
    // in the procControlThread
    public void addObj(Process p, String file){
         synchronized(struct){
              storeSomeWhere(p,file);
    public void run(){
       Iterator i;
      while(boolean){
         synchronized(struct){
            i=struct.iterator();
             while(i.hasNext()){
                MyObj o = (MyObj)i.next();
                 int exitCode;
                  try{
                    exitCode=o.getProcess().exitValue()
                   }catch(IllegalThreadStateException e){
                          // process has not yet finished
                         continue;
                    // process has finished
                    // print in the file where is logged
                   //  the stdout fo the command
                    printSomething(o.getFile(),exitCode);
                     remove(o);
           Thread.sleep(10*1000);    
    // where printSomething
    // create  a Printwriter using a FileOutputStream.well, sometimes i get FileNotFoundException in the printSomething where is mentioned that the file is currently owned by another process.
    do I miss something in the exit code?
    I should using Process.WaitFor()? [ in this case I have to create one thread for controlling one process!]
    -- jdk 1.3.1
    Really thanks in advance.
    T.

    Seems like it should work. Obviously the code you posted is not the same as what you're running though (as it can't compile e.g. while (boolean)), so I'd wonder about what you're really doing.

Maybe you are looking for

  • How do I add a poster to a page curl/turn PDF in InDesign 2014?

    I have created a two-page Christmas card for my company. I used the Adobe TV video to see how to create a SWF file with page curl to import into an InDesign file and keep page turn in a PDF. The only problem is that I can't find how to use the first

  • Cisco Unity Problems Activating Licenses

    We are running a ISM-SRE-300-K9 module on a Cisco 2921 router, which we inherited and did not originally program at this site.  We have purchased L-FL-CUE-MBX-5= licenses but we are having tons of trouble getting them activated.  I am not too familia

  • Using full outer join of subqueries named using with clause

    Hi, I am trying to create a view which is having 2 subqueries vol1 & vol2 with WITH clause. I am joining those 2 subqueries in the main query with FULL OUTER JOIN. When i compile that view in a tool like pl/sql developer, It has been compiled success

  • When Downloading Update for Adobe Reader.

    I am haveing problems installing Current Version of Adobe Reader on my Laptop. I meet the system requirements and when the instalaion get to the point to put it on my computer it says. Can not acess network location. What can i do to fix this.

  • Each specific day in every week shall be marked as an attence in IT2002

    Hi friends, I have an issue as follows: While creating an IT2002 record for an employee, I want to specify the beginning & ending days as well as the weekday (e.g. Monday). Then the system will evaluate the situation as each week Monday is recorded a