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.

Similar Messages

  • 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 ProcessBuilder

    I have an object (textTicket) which is a formatted transaction label. Here is an example:
    CROSS PLAINS QUARRY CROSS PLAINS TN 37049 2549
    MATL SPREADING NOT GUARANTEED
    615-654-9942 TOLL FREE 877-654-9942
    Date: 01/19/2009 04:45:46
    Job No: PU-2008
    Q Num::
    Cust No: 30000001 Src Num::
    Sold To: CASH SALE
    Address: INTERNAL
    NASHVILLE,TN 37202
    Ord By:
    Ord No: Rate Zone:
    Location:THANKS YOU
    Mat. & Haul170.28 Sev Tax:0 Tax16.60
    Acc Total:1308.16
    Total186.88
    3/4 TO 4/67'S
    Gross: 40500 St. Item:
    Tare: 12120 P.O.: MIKE MILLER
    Net: 28380.0
    Net Tons: 14.19
    Proj:
    Truck #: 1
    Hauler: Phy Truck: 248251
    I am attempting to pass this textTicket object to a shell script that will send it out the port for printing. I have tried using the Java Comm API however, we have intermittent problems with the API running on an Oracle Appserver. Sometimes, the data never gets sent to the port. So what I am trying to do is just call a shell script that echos the textTicket out the port via redirection. The problem arise when I use the ProcessBuilder or runtime exec and I have to convert the textTicket to a string via textTicket.toString. The textTicket then losing all of its formatting. Any ideas on how to keep the formatting as I am passing the textTicket to the shell script.

    My example did not save into the post very well. For instance, the first line "Cross Plains Quarry" should be center on the paper. The object contains \t\t to get it center.
    For example on the runtime.exec, I am doing the following
    public void printShell(String port, String string){
         String[] params={"/usr/ts/bin/prttick.sh", string, port};
         try {
                   Process p=Runtime.getRuntime().exec(params);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   SerialCommunicator.logger.debug("error" + e.getMessage());
    The variable string is textTicket.toString();

  • Runtime.exec and setting environment variables

    Runtime.exec and setting environment variables
    I need a decent example which works on Windows.
    Got any?

    Thank you.
    I was hoping for an example of the use of
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Runti
    e.html#exec(java.lang.String,%20java.lang.String[]) or
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Runti
    e.html#exec(java.lang.String,%20java.lang.String[],%20j
    va.io.File) which take environment variable
    information such as PATH.
    The reason is because there is a library which is
    being loaded via loadLibrary (
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Syste
    .html#loadLibrary(java.lang.String) ). However, for
    the child process to find the library the PATH needs
    to be updated.
    Any example regarding changing the PATH variable via
    Java so that libraries can be loaded and processes
    created? (Perhaps, I should make a new post and
    restate the question with this more explicit
    information?)
    That won't work. LoadLibrary occurs in the JVM environment. As I said you can't change the JVM environment via exec().
    If the shared library needs something in the path then you are going to have to set the path before your application starts up.
    If you just need to load the library from someplace that is not on the path then you should be using System.load().

  • Runtime.exec() returns exitValue wrongly on windows XP and Windows 200

    I am trying to execute a batch script from java program using runtime.exec(). I then process exit code for any failures. I see that exit code is always 0 in case of windows XP and Windows 2000. But the same code and script when executed on windows 2003 or unix gives appropriate exit code. Is there any issue with Windows XP and Windows 2000?
    Thanks,
    Sandeep

    I am trying to execute a batch script from java program using runtime.exec(). I then process exit code for any failures. I see that exit code is always 0 in case of windows XP and Windows 2000. But the same code and script when executed on windows 2003 or unix gives appropriate exit code. Is there any issue with Windows XP and Windows 2000?
    Thanks,
    Sandeep

  • Runtime,waitFor and exitValue() methods:child programm never return

    Sorry,my english is really bad!
    i do a programm with tests all the night different java programms.
    I have to compile and after run it.
    My problem is that even if the output and error streams are displayed,each time i have a big programm,the child process always stay blocked.
    I decided to use the dos command ....>>Results.txt to store the datas.
    But the problem is that the wait for and exitvalue methods never returns.

    Hi,
    you must provide a way to read not only the error stream (>>) but also the output stream (>). You can make it from java too. Something like this:
    Runtime rt = java.lang.Runtime.getRuntime();
    Process proc = rt.exec(cmd, null, workdir);
    int inp;
    while ((inp = proc.getInputStream().read()) != -1) {
      System.out.write(inp);
    int err;
    while ((err = proc.getErrorStream().read()) != -1) {
      System.out.write(err);
    proc.waitFor();Best regards,
    Martin

  • Runtime.exec and ServerSocket for IPC...blocking problems

    I have built an IDE for assembling/deploying web applications.
    I am supporting a 'test' mode in the IDE where a compiled 'solution/application' is executed in a separate vm from the IDE using Runtime.exec. For the whole sandbox thing. Don't want a wayward application crashing my IDE.
    Naturally I want a way to communicate start/stop from the IDE to the running application. So sockets are my only choice. Calling process.destroy from my IDE won't invoke a shutdownhandler in the generated application's vm, and I want an orderly shutdown as the generated applications open resources/etc.
    When I execute the generated application from within the IDE the thread code that creates a server socket blocks in the ServerSocket constructor...why?
    When I execute the solution using 'java' outside of my IDE, I can set up a server socket and all works fine.
    My IDE is NEVER creating server sockets waiting for client connects...only the generated application does this. So it isn't a case of the IDE already listening for requests on the same port as the server/generated application.
    Proving the above is that I can manually start my generated application, start my ide, then invoke the menuitem from the IDE that writes a 'close' byte to the client's socket...and the running application DOES shut down.
    Any ideas?

    I have decided on a different approach.
    At first I thought...ok I have the ServerSocket on the wrong 'side'. I then put the ServerSocket code in the always-running IDE and the Socket code on the running/exec'd application. But still a hang on the running application when constructing the Socket.
    I decided instead to call Process.destroy on the running app.
    Given that generated app is running in a separate vm, when it shuts down via process.destroy from the ide...although vm shutdown hooks aren't called...I guess it's ok since a destroy of the vm will release all resources. Not as clean as I'd like though.
    Additionally, I cannot determine 'true' start of application as no socket notification can be done. I merely determine start after a Runtime.exec of jvm process. Subsequent errors in startup will merely be determined by the IDE in process.waitFor or process.exitValue.
    I was getting a wierd socket error when attempting my prior solutions...and not a lot on the web regarding this subject...all relevant posts seemed to be in German/from Germany. Odd. Would need my wife to translate! Mein gott!
    I guess I could've communicated from ide to Runtime.exec'd application via a generated file in filesystem...but this seemed cheesy. Sockets should've been used for ipc between java vms...or so I thought.

  • Problems with Runtime.exec() and certain Unix processes

    Certain Unix processes don't behave correctly when run from Java using Runtime.exec(). This can be seen by running /bin/sh and trying to interact with it interactively. The issue appears to be that /bin/sh (and many other Unix tools) are checking the file handles on the spawned process to see if they are associated with a TTY.
    Is there any way to associate a process spawned by Runtime.exec() with a terminal or alternatively, is there a JNI library available that would setup the process correctly and still provide access to the input and output streams?
    Our objective is to have the flexibility of expect in being able to run and interact with spawned processes. A bug was opened at one point but closed back in 1997 as being a fault in the spawned process, not Java.
    Bug ID: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4058689

    #include <stdio.h>
    void doit() {
    int c;
            while((c=getc(stdin)) != EOF) {
                    printf("%c",c);
    int main() {
            freopen("/dev/tty", "r", stdin);
            doit();
    }This program reopens its standard input against /dev/tty and catenates it to stdout. And voila, it takes its standard input from the terminal, even though it was started with stdin against /dev/null..
    $ gcc b.c -o b
    $./b < /dev/null
    buon giorno
    buon giorno

  • Runtime.exec() and white space

    Hello,
    I am attempting to run a DOS -based hydrological modeling from NT using the Runtime.exec() method. When executing the command:
    "Hec1.exe filename"
    the model runs successfully.
    When I try executing the command:
    "Hec1.exe filename > null", the method recognizes the string array as "Hec1.exe filename>null", which causes the model to fail.
    Here is the code that I use to execute the process:
    Runtime rt = Runtime.getRuntime();
    String[] cmd = new String[4];
    cmd[0] = "Hec1.exe";
    cmd[1] = inputFile;
    cmd[2] = ">";
    cmd[3] = "null";
    Process p = rt.exec(cmd);
    Hopefully, there is some sort of workaround that one of you knows.
    Thanks for your time.
    -Joel Finkel

    and yes that batch file is correct but if you want it to be more usefull change that filename to $1 or %1 i forget which(been working in both *NIX and DOS too long)                                                                                                                                                                                                                                                                                                                                       

  • Runtime.exec() and apostrophe?

    Hi there,
    I try to execute a Unix program using Runtime.exec(). This works as long as I don't need any apostrophe characters:
    works: <path>/<program> <someArguments>doesn't work: <path>/<program> <someArguments> -ls='rm /tmp/test.xml'In the latter case, I get an error message stating a syntax error.
    But when I enter exactly the same command directly into the shell, I don't get an error. Instead, the desired behavior occurs.
    Note: The parameter "-ls" lets the program execute a command once certain criteria are met. But the command in question is not part of the problem. For example, -ls=ll works...
    Thanks in advance for your help! :-)
    btw.: I've already read the "When Runtime.exec() won't" document, so I'm quite sure I didn't run into the shown pitfalls. Well, it could be related to the "Runtime.exec() is not a command line" section, but I haven't been able to figure out how to correct it.
    Kind regards,
    Dennis

    I guess you can remove the test for the SunOS operating system
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.lang.Runtime;
    import java.lang.Process;
    import java.lang.InterruptedException;
    import java.util.StringTokenizer;
    public class JExec {
         private static int lastExitValue = 0;
         public static int getLastExitValue() {
              return lastExitValue;
        public static final String osName= System.getProperty("os.name");
        public static byte[] execUNIXcmd(String commande, byte[] outputData, boolean closeStream) throws NullPointerException {
              Runtime runtime = Runtime.getRuntime();
              Process process = null;
              InputStream inputStream = null;
              OutputStream outputStream = null;
              byte[] bBuf = null;
              String tmpStr = null;
              if (!osName.equals("SunOS")) {
                   System.err.println("Unsupported Operating System");
                   throw new NullPointerException();
              } else {
                   // Dans le cas de SunOs
                   try {
                        process = runtime.exec(commande);
                        outputStream = process.getOutputStream();
                        inputStream = process.getInputStream();
                        if (outputData != null) {
                             outputStream.write(outputData);
                        if (closeStream) outputStream.close();
                        process.waitFor();
                        lastExitValue = process.exitValue();
                        bBuf = new byte[inputStream.available()];
                        inputStream.read(bBuf, 0, inputStream.available());
                        if (!closeStream) outputStream.close();
                        inputStream.close();
                        return bBuf;
                   } catch (InterruptedException e) {
                        System.err.println("ERROR ("+osName+"): Enable to wait the process");
                        throw new NullPointerException();
                   } catch (IOException e) {
                        System.err.println("ERROR ("+osName+"): Enable to read input lines");
                        System.err.println("->"+e.getMessage());
                        throw new NullPointerException();
         public static void main (String[] s) {
              String commande = "echo '$PATH'";
              System.out.println(new String(JExec.execUNIXcmd("sh -e", commande.getBytes(), true)));
    }

  • Runtime.exec and cmd.exe

    Just a quick one here, I think. I'm working on a little tool to merge changes into a document and then copy it over a communications port, and everything seems to be checking out except for that last step. Rather than worrying about streams and whatnot, I'm saving the file to the hard drive; from here, my plan has been to open the DOS prompt and take advantage of its "copy (filename) (port)" command to transfer the file. So in the end, the key line of Java should be something like
    Runtime.getRuntime().exec("cmd.exe copy \"" + fileName + "\" LPT1");My issue here is that the command prompt doesn't seem to want to open using Runtime.exec(). It seems like cmd.exe should do the job -- tossing that into the run menu certainly opens the prompt -- and even just to be sure, I've tried using C:\WINDOWS\system32\cmd.exe explicitly, and both that at cmd.exe without any additional arguments. Strangely, though, the prompt isn't opening, and I'm not getting an I/O error out of it as if I was sending in a bogus command.
    So what am I doing wrong here? What do I have to do to open the DOS prompt?

    As I mentioned, I did try providing the full path to cmd.exe, to no effect.
    Curiously, though, changing "cmd.exe" into "cmd.exe /k" or "cmd.exe /c" both cuased the command to run correctly. Contrary to what they're supposed to do, though, both of them result in the immediate termination of the DOS prompt, even though /k is supposed to cause the window to persist. Any ideas as far as that one goes?

  • Runtime.exec() and security ?

    Hello,
    I have a program where a user can enter a binary path to openssl. The program then appends some hardcoded arguments to the openssl binary to do some crypto operation. I'm using Runtime.exec(String) to execute the command. For example:
    */usr/bin/openssl* smime -sign -certfile ....
    Only the bold part of the command can be chosen by the user.
    I'm a bit concerned about the security and I'm scared that a user could actually execute any command by injecting some shell code by entering for instance "verybadcommand #". I tried this and the execution fails which is good but are there any special things I should keep on mind ?
    Thanks in advance,
    Tex
    Edited by: Tex-Twil on Feb 25, 2009 8:35 AM

    Solved the problem. I was setting the DISPLAY variable when I launched the X application but not the XAUTHORITY variable. Once that was set the X application launched as expected.
    - Bill

  • Runtime.exec() and fork() and Process

    So let me see if I understand this correctly, and if I don't please fill me in. If I call the following piece of codeRuntime.getRuntime().exec("chgrp rcsweb " + path+fs+orgName);
    Runtime.getRuntime().exec("chmod 660 " + path+fs+orgName);where path is the real path to a file, fs is short for File.spearator and orgName is the name of a file, then in the Unix environment, it will fork off a process.
    First, I seem to remember one forum topic that mentioned not forgetting about killing the process returned by exec, so I guess I need to add that to my code.
    Second, since I am forking off this process inside of a J2EE container, am I actually forming off the entire container, or just the Servlet where Runtime is called, or what?
    Third, how can I prevent the error java.io.IOException: Not enough space
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:54)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:546)
    at java.lang.Runtime.exec(Runtime.java:413)
    at java.lang.Runtime.exec(Runtime.java:356)
    at java.lang.Runtime.exec(Runtime.java:320)when I do not have the option of changing my VM size? Is killing the Process (and using waitFor()) going to take care of this issue?
    I appreciate your help.

    OK, after writing a few test programs, it is indeed clear..on unix (at least on solaris) when calling runtime.exec(..) The ENTIRE VM does indeed get forked. Therefore if your current Memory allocation for you VM is sitting at say 64MB (or you initial memory setting), another 64MB process will be created, even if you doing something as a simple
    exec("ls");
    I also tried putting runtime.exec call in its own thread hoping that if it was not in the main thread, that only that process would be forked..to no avail..the entire vm is indeed forked everytime...making runtime.exec damn near useless for server side work, and very dangerious..as you can essentialy assume you always need 2x your memory requirements.
    If anyone has figured out a workaround...any suggestions greatly appreciated.
    Some thoughts on some work-arounds
    1. Run 2 VMs (then when native calls are required..send a message to the 'native-calling vm' (insure its memory footprint is very low)
    2. Write your exec method via JNI (or does JNI calls also result in a fork of the vm on unix..)
    Test code below (threaded version)
    import java.util.*;
    import java.io.*;
    public class test5 extends Thread
         public void run()
              int loops = 0;
              while (true)
                   loops++;
                   System.out.println("---- iteration " loops "---");
                   makeNativeCall();
         public static void main(String[] args)
              try
                   System.out.println("testing on OS: " + System.getProperty("os.name"));
                   // Allocate a nice chunk of memory
                   byte[] bytes = new byte[1024 * 1000 * 50];
                   test5 tst = new test5();
                   tst.start();
                   while (true)
                        Thread.sleep(1000);
         catch(Exception e)
         {e.printStackTrace();}
    public void makeNativeCall()
              Runtime runtime = Runtime.getRuntime();
    InputStream stderr = null;
    InputStream stdout = null;
              OutputStream stdin = null;
    Process proc = null;
    long totalMem = (long)(runtime.totalMemory()/1024);
    long freeMem = (long)(runtime.freeMemory()/1024);
    long usedMem = (long)((totalMem - freeMem));
    System.out.println("VM REPORT: TOTAL(" totalMem") FREE("+freeMem+") USED(" usedMem")" );
    try
    proc = runtime.exec("sleep 1");
    stderr = proc.getInputStream();
    stdout = proc.getErrorStream();
    stdin = proc.getOutputStream();
    String line = null;
    int i = 0;
    String error = "";
    int exitVal = proc.waitFor();
    if (exitVal != 0)
    System.out.println("ERROR " +exitVal);
    System.out.println("DETIAL" +error);
    catch(Exception e)
    e.printStackTrace();
    finally
    if (stderr != null)
    try{stderr.close();}catch(Exception ignore){ignore.printStackTrace();}
                   if (stdout != null)
    try{stdout.close();}catch(Exception ignore){ignore.printStackTrace();}
                   if (stdin != null)
    try{stdin.close();}catch(Exception ignore){ignore.printStackTrace();}
    if (proc != null)
    try{proc.destroy();}catch(Exception ignore){ignore.printStackTrace();}

  • Runtime.exec() and batch files

    I am having a problem on Windows 2000 while trying to execute a batch file with the Runtime.exec() method. Basically, the exit value returned from the call to Runtime.exec(), returned specifically by the waitFor() method in the Process class, is always zero, even if the batch file fails miserably. After looking into batch files further, it seems to me that the only way to get the exit value of the commands run in the batch file back to the Runtime.exec() call is to put "EXIT %ERRORLEVEL%" in the batch file. What this actually does is exit the command(cmd) shell that the batch file was running in with the exit code of the last command run. This is all great when calling the batch file with a Runtime.exec() call, but when you run it in a cmd window, the window closes when the batch file completes, because the call to EXIT exits the entire shell. I guess i'm just wondering, am i correct in assuming the exit value returned to the java process is going to be the exit value of the shell in which the batch file is running? I need to have the exit value actually indicate whether the batch file ran successfully or not, and if i have to put in the EXIT %ERRORLEVE% (which exits the cmd shell with the exit value of the last command run), then i'll do that, but if someone knows a better way of doing this, i am all ears. Thanks in advance

    To run any command from java code, the method is
    Runtime.getRuntime().exec( myCommandString )
    Where, myCommandString is something like "/full/pathname/command".
    If the pathname contains spaces (specifically in Windows), e.g. "c:\program files\windows\notepad", then enclose it in quotes within the quoted string. Or pre-tokenize them into elements of an array and call exec(String[] cmd) instead of exec(String cmd).
    From JDK1.3 there are two new overloaded Runtime.exec() methods. These allow you to specify starting directory for the child process.
    Note, there is a gotcha associated with reading output from commands. When the runtime exec's the process, it passes to it 3 streams, for stdin, stdout, and stderr; the out and err are buffered but the buffer size isn't very big. When your process runs, it reads (if needed) from in, and writes to out and err.
    If it doesn't write more than the buffer-size, it can run to completion.
    But if it tries to write more data to one or the other stream than the buffer can hold, the write blocks, and your process hangs, waiting for you to empty the buffer so it can write some more.
    So after the exec call, get the streams, and read from them in a loop until they both hit end-of-stream (don't block on either one, just read whatever is available from each, each loop iteration).
    Then when the streams have ended, call the process.waitFor() method to let it finish dying.
    Now, here is a code snippet how you achieve this.
    String strCommand = "cmd.exe /c " + strCommand;
    // For Solaris / unix it will be
    // String strCommand = "/usr/cobra/sol/runInstaller.sh";
    boolean bWait = true;
    //execute the command
    try
         Runtime r = Runtime.getRuntime();
         Process pr = r.exec(strCommand);
         Process pr = r.exec(callAndArgs);
         BufferedInputStream bis =new BufferedInputStream(pr.getInputStream ());
         int c=0;
         /** Outlet for IO for the process **/
         while (c!=-1)
              c=bis.read();
         /**Now wait for the process to get finished **/
         if(bWait == true)
              pr.waitFor();
              pr.destroy();
    catch(Exception e)
         System.out.println("Could not execute process " + strCommand);
         return(false);

  • Runtime.exec() and Mozilla

    Hi all. I'm not sure if this is the correct forum for this question but I use Runtime.exec() to create a new mozilla process. I have no problem creating the process itself but I need to have a way to communicate with the process to determine whether or not a local file has been successfully loaded into the browser. I programmatically load some html content in mozilla and I need to get the current "state" of the browser (i.e. is the content fully loaded and displayed on the screen or is mozilla still busy loading the html file?). I figure that the only way to determine this state is to get the Processes input stream and to read data from that stream but I don't know if mozilla writes data to it's output stream that indicates what state the application is in. Does anybody have a solution to this problem (Whether using streams or some other approach)? Thanks in advance.

    It may be possible to hack Mozilla to get that sort of information, although most likely its security is good enough to prevent attacks of that kind. But in any case Runtime.exec() isn't going to help.

Maybe you are looking for

  • My Ipod touch no longer recognized by Itunes.

    Works fine with Windows 8, but not picked up by Itunes. I've already restarted Itunes, restarted local service for Ipod and restarted computer and Ipod.I have already visited http://support.apple.com/kb/ts1363 

  • How to set up user account and share folders

    We are a family of four sharing our first iMac. I would like to set up one account for my wife and I and one account for my kids on which I plan to enable Parental Controls. I have struggled with setting up my kids user account. After setting up a St

  • Updating to iPhoto 9.5.1 lost all my photos. How can I retreive them?

    Updating to iPhoto 9.5.1 lost all my photos. How can I retreive them? I'm on a MacBook Pro using OS X version 10.9.5. When I attempted to edit a photo in the version I had at the time, I got a message that I must update to iPhoto 9.5.1 to use that fu

  • Status of Sales Order Open Even after assigning Reason for Rejection.

    Hi All, I am facing with a basic problem wherein even after assigning a reason for rejection status for a sales order, the sales order numbere is appearing in  the list of Open Sales Order(VA05). Also another case is i created a sales order with one

  • Which AC adapter do i use in India?

    Hi, I have a Powerbook and want to use it in India. Mine runs on 110V and is made for flat pin sockets. In India the voltage is 220-240 V and the sockets are round shaped. Can anyone suggest the following - 1. Name of the AC adapter that can be used.