InputStream hung from Runtime.getRuntime().exec

Dear all,
I am trying to use the following code to run a Runtime.getRuntime().exec("my_selection.exe") method and redirect all the output from the process to my JTextArea.
My program is an executable called "my_selection.exe", which runs under DOS something like:
My Selection Utilities:
type the command -
o : open an item
l : list subitems
q : exit
Please select your options:But when I run my Test program, the above selection menu does not show in my JTextArea. Only after I type q (which is exit command in my_selection), will all the output shown in TextArea.
I tested the inputstream.available(), but it always == 0.
Anyone can help point me out what is wrong here?
BTW, when I use the same program to run "copy a.txt a" by exec("cmd.exe"), it works ok, no matter whether it prompts for owerwrite the existing file or not.
Many thanks!
I tried the code,
/* part of the code */
public static void main(String[] args) {
     Test t = new Test();
     t.setTitle("Basic GUI");
     t.init(); // init GUI
     t.connect();
     t.show();
private static void log(Object text) {
     getTextArea().setCaretPosition(getTextArea().getText().length());
     getTextArea().setText(getTextArea().getText() + text.toString() + "\n");
private Thread getInputStreamListener() {
     if(listener == null) {
          Runnable runnable = new Runnable() {
               public void run() {
                    try {
                         String text = "";
                         while (true) {
                              while (inputStream.available()==0) {
                                   Thread.currentThread().sleep(100);
                              byte[] bytes = new byte[inputStream.available()];
                              inputStream.read(bytes);
                              text = new String(bytes);
                              log("> " + text);
                    catch(Exception e) {
                         handleException(e);
          listener = new Thread(runnable);
          listener.setName("out listener");
          listener.setPriority(2);
          listener.start();
     return listener;
private Thread getErrorStreamListener() {
     if(listener == null) {
          Runnable runnable = new Runnable() {
               public void run() {
                    try {
                         String text = "";
                         while (true) {
                              while (errorStream.available()==0) {
                                   Thread.currentThread().sleep(100);
                              byte[] bytes = new byte[errorStream.available()];
                              errorStream.read(bytes);
                              text = new String(bytes);
                              log("> " + text);
                    catch(Exception e) {
                         handleException(e);
          listener = new Thread(runnable);
          listener.setName("out error listener");
          listener.setPriority(2);
          listener.start();
     return listener;
private static void handleException(Throwable t) {
     log(t);
private void connect() {
     try{
          process = Runtime.getRuntime().exec(new String[] {"my_selection.exe"});
          inputStream = new BufferedInputStream(process.getInputStream());
          outputStream = new BufferedOutputStream(process.getOutputStream());
          errorStream = new BufferedInputStream(process.getErrorStream());
          getInputStreamListener();
          getErrorStreamListener();
     catch(Exception e) {
          log(e);

Note in the above code all "listener" variable in:
private Thread getErrorStreamListener() method
show be "listener1".
Even I changed it, it does not work either.
Please help.
Thanks!

Similar Messages

  • Executing Batch files from Runtime.getRuntime().exec

    Can we execute batch files from Runtime.getRuntime().exec() method.
    Regards,
    Nalini

    hi,
    import java.io.IOException;
    class BatchFileTest{
         public static void main(String args[]){
              try{
              Runtime r = Runtime.getRuntime();
              Process p = r.exec("startcmd.bat");
              catch(IOException en){
                   en.printStackTrace();
    -Regards
    Manikantan

  • Inconsistent exit code from Runtime.getRuntime().exec

    I'm getting non-deterministic behavior from a call to a native process. Here is the code:
    public class Test {
    public static void main (String[] pArgs) {
    try {
    String cmd[] = { "cmp", "-s",
    pArgs[0],
    pArgs[1] };
    System.err.println("running command: ");
    Process p = Runtime.getRuntime().exec(cmd);
    System.err.println("getting exitcode...");
    int exitcode = p.waitFor();
    System.err.println(exitcode);
    System.err.println(p.exitValue());
    } catch(Exception e) {
    System.err.println("Caught exception while executing cmd");
    e.printStackTrace();
    And here is the output:
    bock@homeruns[~/work/index]10:08> java Test output output.old
    running command:
    getting exitcode...
    0
    0
    bock@homeruns[~/work/index]10:08> java Test output output.old
    running command:
    getting exitcode...
    1
    1
    bock@homeruns[~/work/index]10:08> java Test output output.old
    running command:
    getting exitcode...
    0
    0
    they should all be 1's because the files are different. when i run it on the command line i get:
    bock@homeruns[~/work/index]10:13> cmp -s output output.old ; echo $?
    1
    any help would definitely be appreciated!
    thanks,
    roger

    thanks for the link. i read through it but it doesn't seem to address why the exit code would be inconsistently reported. the other problems described by that link don't seem to apply to this case because i have not experienced hanging and there is no standard input, standard output, or standard error associated with "cmp -s" - all it does is return the appropriate exit code.
    should i be reporting this as a bug to sun? up till recently i've been assuming it was a problem with my code but now i'm not so sure...

  • How to get return value from Java runtime.getRuntime.exec?

    I'm running shell commands from an Oracle db (11gr2) on aix.
    But, I would like to get a return value from a shell comand... like you get with "echo $?"
    I use a code like
    CREATE OR REPLACE JAVA SOURCE NAMED common."Host" AS
    import java.io.*;
    public class Host {
      public static int executeCommand(String command) {
        int retval=0;
        try {
            String[] finalCommand;
            finalCommand = new String[3];
            finalCommand[0] = "/bin/sh";
            finalCommand[1] = "-c";
            finalCommand[2] = command;
          final Process pr = Runtime.getRuntime().exec(finalCommand);
          pr.waitFor();
       catch (Exception ex) {
          System.out.println(ex.getLocalizedMessage());
          retval=-1;
        return retval;
    /but I do not get a return value... because I don't know how to get return value..
    Edited by: user9158455 on 22-Sep-2010 07:33

    Hi,
    Have your tried pr.exitValue() ?
    I think you also need a finally block that destroys the subprocess
    Regards
    Peter

  • Running curl command from a java program using Runtime.getRuntime.exec

    for some reason my curl command does not run when I run it from within my java program and errors out with "https protocol not supported". This same curl command however runs fine from any directory on my red hat linux system.
    To debug the problem, I printed my curl command from the java program before calling Runtime.getRuntime.exec command and then used this o/p to run from the command line and it runs fine.
    I am not using libcurl or anything else, I am running a simple curl command as a command line utility from inside a Java program.
    Any ideas on why this might be happening?

    thanks a lot for your response. The reason why I am using curl is because I need to use certificates and keys to gain access to the internal server. So I use curl "<url> --cert <path to the certificate>" --key "<path to the key>". If you don't mid could you please tell me which version of curl you are using.
    I am using 7.15 in my system.
    Below is the code which errors out.
    public int execCurlCmd(String command)
              String s = null;
              try {
                  // run the Unix "ps -ef" command
                     Process p = Runtime.getRuntime().exec(command);
                     BufferedReader stdInput = new BufferedReader(new
                          InputStreamReader(p.getInputStream()));
                     BufferedReader stdError = new BufferedReader(new
                          InputStreamReader(p.getErrorStream()));
                     // read the output from the command
                     System.out.println("Here is the standard output of the command:\n");
                     while ((s = stdInput.readLine()) != null) {
                         System.out.println(s);
                     // read any errors from the attempted command
                     System.out.println("Here is the standard error of the command (if any):\n");
                     while ((s = stdError.readLine()) != null) {
                         System.out.println(s);
                     return(0);
                 catch (IOException e) {
                     System.out.println("exception happened - here's what I know: ");
                     e.printStackTrace();
                     return(-1);
         }

  • Strange behaviour of Runtime.getRuntime().exec(command)

    hello guys,
    i wrote a program which executes some commands in commandline (actually tried multiple stuff.)
    what did i try?
    open "cmd.exe" manually (administrator)
    type "echo %PROCESSOR_ARCHITECTURE%" and hit enter, which returns me
    "AMD64"
    type "java -version" and hit enter, which returns me:
    "java version "1.6.0_10-beta"
    Java(TM) SE Runtime Environment (build 1.6.0_10-beta-b25)
    Java HotSpot(TM) 64-Bit Server VM (build 11.0-b12, mixed mode)"
    type "reg query "HKLM\SOFTWARE\7-zip"" returns me:
    HKEY_LOCAL_MACHINE\SOFTWARE\7-zip
    Path REG_SZ C:\Program Files\7-Zip\
    i wrote two functions to execute an command
    1) simply calls exec and reads errin and stdout from the process started:
    public static String execute(String command) {
              String result = "";
              try {
                   // Execute a command
                   Process child = Runtime.getRuntime().exec(command);
                   // Read from an input stream
                   InputStream in = child.getInputStream();
                   int c;
                   while ((c = in.read()) != -1) {
                        result += ((char) c);
                   in.close();
                   in = child.getErrorStream();
                   while ((c = in.read()) != -1) {
                        result += ((char) c);
                   in.close();
              } catch (IOException e) {
              return result;
         }the second function allows me to send multiple commands to the cmd
    public static String exec(String[] commands) {
              String line;
              String result = "";
              OutputStream stdin = null;
              InputStream stderr = null;
              InputStream stdout = null;
              // launch EXE and grab stdin/stdout and stderr
              try {
                   Process process;
                   process = Runtime.getRuntime().exec("cmd.exe");
                   stdin = process.getOutputStream();
                   stderr = process.getErrorStream();
                   stdout = process.getInputStream();
                   // "write" the parms into stdin
                   for (int i = 0; i < commands.length; i++) {
                        line = commands[i] + "\n";
                        stdin.write(line.getBytes());
                        stdin.flush();
                   stdin.close();
                   // clean up if any output in stdout
                   BufferedReader brCleanUp = new BufferedReader(
                             new InputStreamReader(stdout));
                   while ((line = brCleanUp.readLine()) != null) {
                        result += line + "\n";
                   brCleanUp.close();
                   // clean up if any output in stderr
                   brCleanUp = new BufferedReader(new InputStreamReader(stderr));
                   while ((line = brCleanUp.readLine()) != null) {
                        result += "ERR: " + line + "\n";
                   brCleanUp.close();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              return result;
         }so i try to execute the commands from above (yes, i am using \\ and \" in java)
    (1) "echo %PROCESSOR_ARCHITECTURE%"
    (2) "java -version"
    (3) "reg query "HKLM\SOFTWARE\7-zip""
    the first function returns me (note that ALL results are different from the stuff above!):
    (1) "" <-- empty ?!
    (2) java version "1.6.0_11"
    Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
    Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing)
    (3) ERROR: The system was unable to find the specified registry key or value.
    the second function returns me:
    (1) x86 <-- huh? i have AMD64
    (2) java version "1.6.0_11"
    Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
    Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing)
    (3) ERROR: The system was unable to find the specified registry key or value.
    horray! in this version the java version is correct! processor architecture is not empty but totally incorrect and the reg query is still err.
    any help is wellcome
    note: i only put stuff here, which returns me strange behaviour, most things are working correct with my functions (using the Runtime.getRuntime().exec(command); code)
    note2: "reg query "HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0" /t REG_SZ" IS working, so why are "some" queries result in ERR, while they are working if typed by hand in cmd.exe?

    ok, i exported a jar file and execute it from cmd:
    java -jar myjar.jar
    now the output is:
    (1) "" if called by version 1, possible to retrieve by version 2 (no clue why!)
    (2) "java version "1.6.0_10-beta"
    Java(TM) SE Runtime Environment (build 1.6.0_10-beta-b25)
    Java HotSpot(TM) 64-Bit Server VM (build 11.0-b12, mixed mode)"
    (3) C:\Program Files\7-Zip\
    so all three problems are gone! (but its a hard way, as i need both functions and parse a lot of text... :/ )
    thanks for the tip, that eclipse changes variables (i really did not knew this one...)

  • PROBLEM in executing a shell command through Runtime.getRuntime().exec()

    Hi all,
    I was trying to execute the following code:
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.Statement;
    import java.sql.ResultSet;
    * Created on Mar 13, 2007
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    * @author 195092
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class ClassReportDeleteDaemon {
         ClassReportDeleteDaemon()
         public static void main(String[] args) throws Exception
              Connection conn = null;
              Statement stmt = null;
              ResultSet rs;
              String strQuery = null;
              String strdaysback = null;
              String delstring = null;
              int daysback;
              try
                   System.out.println("REPORT DELETION ::: FINDING DRIVER");               
                   Class.forName("oracle.jdbc.driver.OracleDriver");
              catch(Exception e)
                   System.out.println("REPORT DELETION ::: DRIVER EXCEPTION--" + e.getMessage());
                   System.out.println("REPORT DELETION ::: DRIVER NOT FOUND");
              try
                   String strUrl = "jdbc:Oracle:thin:" + args[0] + "/" + args[1] + "@" + args[2];
                   System.out.println("REPORT DELETION ::: TRYING FOR JDBC CONNECTION");
                   conn = DriverManager.getConnection(strUrl);
                   System.out.println("REPORT DELETION ::: SUCCESSFUL CONNECTION");
                   while(true)
                        System.out.println("WHILE LOOP");
                        stmt = conn.createStatement();
                        strQuery = "SELECT REP_DAYS_OLD FROM T_REPORT_DEL";
                        rs = stmt.executeQuery(strQuery);
                        while(rs.next())
                             strdaysback = rs.getString("REP_DAYS_OLD");
                             //daysback = Integer.parseInt(strdaysback);
                        System.out.print("NO of Days===>" + strdaysback);
                        delstring = "find /tmp/reports1 -name " + "\"" + "*" + "\"" + " -mtime +" + strdaysback + " -print|xargs rm -r";
                        System.out.println("DELETE STRING===>" + delstring);
                        Process proc = Runtime.getRuntime().exec(delstring);
                        //Get error stream to display error messages encountered during execution of command
                        InputStream errStream=proc.getErrorStream();
                        //Get error stream to display output messages encountered during execution of command
                        InputStream inStream = proc.getInputStream();
                        InputStreamReader strReader = new InputStreamReader(errStream);
                        BufferedReader br = new BufferedReader(strReader);
                        String strLine = null;
                        while((strLine=br.readLine())!=null)
                             System.out.println(strLine);
                   }     //end of while loop
              }     //end of try
              catch (Exception e)
                   System.out.println("REPORT DELETION ::: EXCEPTION---" + e.getMessage());
                   conn.close();
         }     //end of main
    }     //end of ClassReportDeleteDaemon
    But it is giving the error "BAD OPTION -print|xargs". The command run well in shell.
    Please help.
    Thanking u.......

    Since the pipe '|' is interpreted by the shell then you need the shell to invoke your command
            String[] command = {"sh","-c","find /tmp/reports1 -name " + "\"" + "*" + "\"" + " -mtime +" + strdaysback + " -print|xargs rm -r"};
            final Process process = Runtime.getRuntime().exec(command);
      You should also read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html at least twice and implement the recommendation regarding stdout and stderr.
    P.S. Why are you not using Java to find and delete these files?
    Message was edited by:
    sabre150

  • Runtime.getRuntime().exec hangs and doesn't print the output

    Hi,
    I have written the following code to execute the command "psexec ipaddress -u userid -p password -l -c execute.exe >> c:/25_showoutpout.txt" and print the output in 25_showoutpout.txt file.
    import java.io.*;
    public class ExecTest{
         public static void main(String args[]) throws IOException{
         String args1 = "psexec ipaddress -u userid -p password -l -c execute.exe >> c:/25_showoutpout.txt";
         try{
         Process p=Runtime.getRuntime().exec(args1);
    int i = p.waitFor();
         System.out.println("Done.with time "+i);
         }catch(Exception e){
              System.out.println("The error is "+e);
    But this program hangs and creates a blank 25_showoutpout.txt file.In the process list I can see the process running, but it doesn't redirect the output in the txt file.When i run the command from the command line it runs fine.Please help me.
    Thanks in advance

    Hi,
    I have written the following program to get the output.But still the required output is not coming in the console file.Only the messages that gets printed in the parent console that is coming in the file.But the expected output is to get the messages from the child window which gets executed while the .exe runs.
    import java.io.*;
    public class RuntimeExecTest{
    public static void main(String args[]){
    String s = null;
    String result= null;
    int count =0;
    try{
              // read the output from the command
    String cmd = "cmd.exe /c D:/installer/PsTools.zip/PsTools/psexec.exe ipaddress -u userid -p password -l -c excute.exe >> C:/RuntimeExec_25.txt";
         Process p = Runtime.getRuntime().exec(cmd);
         InputStream is = p.getInputStream();
         // Get the std in to the process.
         OutputStream os = p.getOutputStream();
         // Get the std err from the process.
         InputStream es = p.getErrorStream();
         // Create readers for those streams.
         BufferedReader reader = new BufferedReader(new InputStreamReader(is));
         BufferedReader errReader = new BufferedReader(new InputStreamReader(es));
         String line;               
         // Read STDOUT into a buffer.
         // If no STDOUT check STDERR.
         while((line = errReader.readLine()) != null){
              // Do something with data here if you wish.
         System.out.println( line );
         while((line = reader.readLine()) != null){
              // Do something with data here if you wish.
         System.out.println( line );
         System.exit(0);
    catch( Exception ex )
    ex.printStackTrace();
    }

  • Runtime.getRuntime().exec() does not return

    Hello,
    I am running into a case where the call to Runtime.getRuntime.exec(command) does not return. The scenario is that the main thread spawns another thread which calls the Runtime.exec(). Since the call does not return, both threads seems to be hung. The jstack output from the main thread shows
    ----------------- t@2 -----------------
    0xfeedab45 ___lwp_cond_wait + 0x15
    0xfeb4030d void os::PlatformEvent::park() + 0xa9
    0xfebadd48 void ObjectMonitor::wait(long long,bool,Thread*) + 0x26c
    0xfe770287 void ObjectSynchronizer::wait(Handle,long long,Thread*) + 0xef
    0xfe76ffbb JVM_MonitorWait + 0x20f
    0xfb20a032 * java.lang.Object.wait(long) bci:0 (Interpreted frame)
    0xfb20308d * java.lang.Thread.join(long) bci:38 line:1143 (Interpreted frame)
    0xfb20308d * java.lang.Thread.join() bci:2 line:1196 (Interpreted frame)
    0xfb20308d * DataLoader.checkThreadGroup() bci:92 line:316 (Interpreted frame)
    0xfb202f27 * DataLoader.checkTables(int) bci:1 line:336 (Interpreted frame)
    0xfb202f69 * DataLoader.runLoad(int, java.lang.String, java.lang.String, java.lang.String, com.sabre.fltsked.apm.util.FSIOHelper)
    ... more below ....
    So it is waiting for the spawned thread on a join()
    And the jstack dump for the thread that called exec() is
    ----------------- t@70 -----------------
    0xfeed7409 __lwp_park + 0x19
    0xfeed1be7 cond_wait_queue + 0x5e
    0xfeed1f64 cond_wait_common + 0x1db
    0xfeed20d2 condwait + 0x7b
    0xfeed20fd cond_wait + 0x21
    0xfeed2136 pthread_cond_wait + 0x1b
    0x9741082a soft_delete_object_cleanup + 0x57
    0x97410906 soft_delete_object + 0x5b
    0x97410953 soft_delete_all_objects_in_session + 0x2e
    0x97407b7a soft_delete_session + 0xec
    0x97407860 soft_delete_all_sessions + 0x3c
    0x97402525 finalize_common + 0x66
    0x974026ae softtoken_fini + 0x34
    0x974355f9 _fini + 0x21
    0xfefdd49a remove_hdl + 0x766
    0xfefd8be9 dlclose_core + 0xb1
    0xfefd8c1d dlclose_intn + 0x21
    0xfefd8c96 dlclose_check + 0x2a
    0xfefd8d00 dlclose + 0x38
    0x97480aeb pkcs11_slottable_delete + 0xb1
    0x9747c691 finalize_common + 0xe2
    0x9747c6e0 pkcs11_fini + 0x3e
    0x9747c3bf pkcs11_fork_child + 0x73
    0xfee628b8 postforkchild_handler + 0x2f
    0xfeeca9ec fork + 0x12e
    0xfe338029 Java_java_lang_UNIXProcess_forkAndExec + 0x395
    0xfb20a032 * java.lang.UNIXProcess.forkAndExec(byte[], byte[], int, byte[], int, byte[], boolean, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor) bci
    :0 (Interpreted frame)
    0xfb202f69 * java.lang.UNIXProcess.<init>(byte[], byte[], int, byte[], int, byte[], boolean) bci:62 line:53 (Interpreted frame)
    0xfb20308d * java.lang.ProcessImpl.start(java.lang.String[], java.util.Map, java.lang.String, boolean) bci:182 line:65 (Interpreted frame)
    0xfb202f27 * java.lang.ProcessBuilder.start() bci:112 line:452 (Interpreted frame)
    0xfb202f27 * java.lang.Runtime.exec(java.lang.String[], java.lang.String[], java.io.File) bci:16 line:593 (Interpreted frame)
    0xfb202f27 * java.lang.Runtime.exec(java.lang.String, java.lang.String[], java.io.File) bci:69 line:431 (Interpreted frame)
    0xfb202f27 * java.lang.Runtime.exec(java.lang.String) bci:4 line:328 (Interpreted frame)
    0xfb202f27 *SQLLoad(java.lang.StringBuffer) bci:181 line:51 (Interpreted frame)
    0xfb202e61 *FSLoadThread.run() bci:84 line:54 (Interpreted frame)
    The command I am trying to exec is "sqlldr" and I do have it in my PATH variable. Why is that the call to exec does not return? Any ideas?
    This is on jdk1.6.0_17
    Thanks,
    Bijoy.

    It has definitely forked, and this is the child process. It says so. If it was the parent process it would just show Java code related to launching processes. That does not involve PKCS11. After the fork there are two identical processes with the same stack: the child process of the fork goes on to replace itself with the target command via Unix exec(), which it doesn't look like it is succeeding at. The parent process doesn't do much at all, probably just housekeeping and then a Unix wait() for Process.waitFor() to hook into.

  • Runtime.getRuntime().exec(...) problems and exit codes

    Hi,
    I am trying to launch an application 4 times with different arguments from a Java app. I have tried doing it sequentially and in four different threads, but the results are the same: sometimes the 4 of them are properly launched, sometimes (the most of the times) only 3 are launched and sometimes only 2. I have tried with cmd and cmdarray[] as parameters for exec but the results are the same.
    This is one of the four threads I use:
    Runnable r1 = new Runnable(){
                        public void run(){
                             String ecgCommand = "./flute -S -m:" + Config.ECGS_FLUTE_IP + " -p:" + Config.ECGS_FLUTE_PORT + " -F:" + Config.ECGS + " -r:" + Config.ECGS_FLUTE_RATE + " -C";
                             System.out.println(ecgCommand);
                             InputStream ecgsStream = null;
                             InputStreamReader isr = null;
                             BufferedReader br = null;
                             try{
                                  ecgsProcess = Runtime.getRuntime().exec(ecgCommand, null, new File(Config.HOME_PATH + Config.FLUTE_PATH));
                                  String line;
                                  ecgsStream = ecgsProcess.getInputStream();
                                  isr = new InputStreamReader(ecgsStream);
                                  br = new BufferedReader(isr);
                                  StyledDocument styleDoc = mm.ecgFluteMessages.getStyledDocument();
                                  Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
                                  while((line = br.readLine()) != null && running){
                                       if(styleDoc.getLength() > 25000)     mm.ecgFluteMessages.setText("");
                                       styleDoc.insertString(styleDoc.getLength(), line+ "\n", def);
                                       mm.ecgFluteMessages.setCaretPosition(mm.ecgFluteMessages.getDocument().getLength());
                                  System.out.println(ecgsProcess.waitFor());
                             }catch(Exception e){
                                  try {
                                       br.close();
                                       isr.close();
                                       ecgsStream.close();
                                  } catch (Exception e1) {
                                       e.printStackTrace();
                   new Thread(r1).start();Adding a Thread.sleep between runnables doesn't have any effect.
    In addition, those processes that are not properly launched return an exit value of 255. I have searched for its meaning but I have found nothing. Could anybody tell me where can I find a list of the JVM exit codes in order to guess what is happening?
    Can anybody help me with this issue? Help is much appreciated.
    Thanks a lot

    I have been looking for it but it seems it has not any exit code list or any documentation regarding this. Anyway, I think 255 is a JVM error code (the last one, errors are numbered in modulo 256) which means that the error has nothing to do with JVM but with the application execution (flute in my case).
    I have added a prompt for the errorStream and I have this message for the 255 exited programs:
    not well-formed (invalid token) at line 15+
    And the four commands are like this:
    *./flute -S -m:239.255.255.253 -p:60102 -F:./ecgs -r:150 -C*
    *./flute -S -m:239.255.255.252 -p:60103 -F:./ads -r:150 -C*
    *./flute -S -m:239.255.255.251 -p:60104 -F:./pushvod -r:50 -C*
    *./flute -S -m:239.255.255.250 -p:60105 -F:./banners -r:150 -C*
    So, as the process is sometimes initialized properly and others it is not, it seems that there is a problem with the tokenizing of the command not happening always. As I have tried it with a single command line and with an array of command strings (the first for "./flute" and the followings for each argument) with the same results I can't understand why is this problem happening sometimes. Happening always would help me in giving a clue but that's not the case.
    Any idea? Thanks a lot.
    Edited by: dulceangustia on Apr 3, 2008 3:41 AM

  • Runtime.getRuntime().exec question

    Hi
    I have written an program where i need to open files on my computer with specific commands, but it wont work correctly.
    It looks something like this in my Tools class:
    public void setCustomCmd (String cmd) {
              customOpenCmd = cmd;
         public void openCustom (String[] path) {          
              String[] uu = new String[path.length + 1];
              uu[0] = customOpenCmd;
              for (int i = 1;i < uu.length;i++) {
                   uu[i] = path[i - 1];
              try {
                   Process p = Runtime.getRuntime().exec(uu);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         }I am trying to open an array of files with the specified command, like some movies with gmplayer. (im using linux, but it would be good to make this method platform independent). The thing is it "kind of" works. When i give an array with paths to smplayer (an frontend for mplayer) they will be added to the playlist and i can play the movies, but smplayer behaves strange. When i try to open the settings or the file info for instance, smplayer just freezes. Gmplayer also "kind of" works, until i try to close it. It will freeze and i have to kill the process. (in both cases the movie still plays, but the frontend for mplayer itself freezes).
    So far i have been able to solve every problem in my learning process of java (and programming in general) with google, but im just unable to make any progress with this problem (and i REALLY have tried everything i can think of). So, can anyone help me?
    Also, smplayer does write some output to the terminal when i run it, do i need to handle that from java somehow as well?
    Thanks in advice.

    Hah! now i managed to make it work perfectly. Here is my code (maybe its a bit ugly since I'm quite new to programming in general, but it may help someone who tries to accomplish the same thing):
    public void setCustomCmd (String cmd) {
              customOpenCmd = cmd;
         public void openCustom (String[] path) {          
              String[] uu = new String[path.length + 1];
              uu[0] = customOpenCmd;
              for (int i = 1;i < uu.length;i++) {
                   uu[i] = path[i - 1];
              RunCmd zzz = new RunCmd(uu);
              zzz.start();
         private class RunCmd extends Thread
             Process proc;
             String[] cmd;
             RunCmd(String[] cmdIn)
                cmd = cmdIn;
             public String[] getCmd() {
                  return cmd;
             public boolean setCmd(String[] cmdIn) {
                  // Don't change the command in case this thread is alive.
                  if (this.isAlive()) {
                       return false;
                  cmd = cmdIn;
                  return true;
             public void run()
                  try
                       // Execute the command in run to avoid problems in case someone forgets to call
                       // run and the process "kind of" works as an result.
                       Runtime rt = Runtime.getRuntime();
                       proc = rt.exec(cmd);
                     // any error message?
                     StreamGobbler errorGobbler = new
                         StreamGobbler(proc.getErrorStream(), "ERR");           
                     // any output?
                     StreamGobbler outputGobbler = new
                         StreamGobbler(proc.getInputStream(), "OUT");
                     // kick them off
                     errorGobbler.start();
                     outputGobbler.start();
                     // any error???
                     int exitVal = proc.waitFor();
                     log.print(customOpenCmd + ":<BR>" + "<font color=green>ExitValue: " + exitVal + "</font color=green>");
                     log.print("");
                 } catch (Throwable t)
                     t.printStackTrace();
         private class StreamGobbler extends Thread
             InputStream is;
             String type;
             OutputStream os;
             StreamGobbler(InputStream is, String type)
                 this(is, type, null);
             StreamGobbler(InputStream is, String type, OutputStream redirect)
                 this.is = is;
                 this.type = type;
                 this.os = redirect;
             public void run()
                 try
                     PrintWriter pw = null;
                     if (os != null)
                         pw = new PrintWriter(os);
                     InputStreamReader isr = new InputStreamReader(is);
                     BufferedReader br = new BufferedReader(isr);
                     String line=null;
                     while ( (line = br.readLine()) != null)
                         if (pw != null)
                             pw.println(line);
                         System.out.println(customOpenCmd + ": " + type + ">" + line);
                         // log.printNoTime(customOpenCmd + ": " + type + ">" + line); So much output, my log is 2 slow :p
                     if (pw != null)
                         pw.flush();
                 } catch (IOException ioe)
                     ioe.printStackTrace(); 
         }This executes the command and lets the program continue even if the execition still runs. I have only tried this a few times, so if i encounter problems with this code i will post the solution if i manage to find it.

  • Runtime.getRuntime().exec() problem while getting Mozilla version.

    Hi all,
    I've trying to get the current mozilla version in Java side using
    Runtime.getRuntime().exec(). The sample code is as below.
    I've tested two cases using exec(), as case# 1 and case# 2.
    The result is after the code.
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(new String[] {"mozilla", "-remote"}); //case# 1
    //Process proc = rt.exec(new String[] {"mozilla", "-version"}); //case# 2
    InputStream stderr = proc.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    System.out.println("<ERROR>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    System.out.println("</ERROR>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t) {
    t.printStackTrace();
    // execute "mozilla -remote"(case# 1)
    $ java TestExec
    <ERROR>
    -remote requires an argument
    </ERROR>
    Process exitValue: 1
    // execute "mozilla -version"(case# 2)
    $ java TestExec
    <ERROR>
    </ERROR>
    Process exitValue: 0
    I'm just surprised that why case# 2 couldn't get the returned version string as case #1 ? Since there will be version string be returned from command line:
    $ mozilla -version
    Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.0.1) Gecko/20020830, build 2002083014
    Could anybody explain the problem or give any solution ?
    Thanks.
    -George.

    Hi all,
    One more question here.
    While I use Runtime.getRuntime().exec() to execute some commands,
    the commands may fail for some reason. Generally, they will return with the exit
    value set to 1 or others. But sometime, before waitFor() exits, there is a popped up
    dialog giving some info, and only after I click the "OK" button, it dispears, and
    waitFor() returns the exit value.
    So I'm not sure that could I suppress this popped up dialog, and make it run
    just like other commands ? I mean, just get the exit value by waitFor() without user
    interferance ?
    Thanks.
    -George.

  • Runtime.getRuntime().exec problems running with applet

    Hi,
    I am running the command
    Process prc = Runtime.getRuntime().exec("net config workstation");
    InputStream in = prc.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    line = br.readLine();
    When running from an application(/stand alone program) on Win-NT it runs fine. But when i include the same code in an Applet and try to run.
    It doesnt return any thing. I see the DOS-prompt open and close and i can also see the required output generated on the DOS prompt, but the program doesnt return any results(null) in the InputStream.
    I even tried to get the ErrorStream incase it is writing some error but it doesnt write anything.
    I tried running some other commands like (cmd.exe /c set) which were able to run on both application as well as from the applet.
    I have tried giving the "net config workstation" command in all flavors
         String[] cmd = new String[3];
         cmd[0] = "cmd.exe";
         cmd[1] = "/C";
         cmd[2] = "net config workstation";     
    And      
         String[] cmd = new String[3];
         cmd[0] = "net.exe";
         cmd[1] = "config";
         cmd[2] = "workstation";          
    AND
         String[] cmd = new String[5];
         cmd[0] = "cmd.exe";
         cmd[1] = "/C";
         cmd[2] = "net.exe";
         cmd[3] = "config";
         cmd[4] = "workstation";     
    AND giing the full path as
    C:\winnt\system32\net.exe config workstation
    But still it doesnt work.
    Can anybody please suggest what is the problem.Its Urgent.....
    Well the purpose of this is to get users system properties like the Logon Domain , server name etc.... or else can anybody suggest a better way to obtain this information.....
    Your reply will be highly appriciated...
    Thanks in Advance......

    Thanks for atleast replying.....
    Sorry, i forgot to mention.... yes OfCourse, i am using an Signed Applet..... That how i was able to run the "set" command.....
    I have made sure it is not sucha simple problem..... the thing is as i have mentioned i know that even "net config workstation" works..... cause i see the output on the DOS prompt,.... but this output is not returned to the Applet in the getInputStream()/getErrorStream().....
    Can anybody please suggest a way to get this output..... OR is there some other way to get the machine's domain, server name etc info from the machine....?????
    Thanks in Advance...!!

  • Runtime.getRuntime().exec() - native process

    Hi,
    I want to start a native (openFt) program from within my servlet. Therefore, I use Runtime.getRuntime().exec(String [] cmd). This works fine in my local OC4J container: the process is terminated with error code 0 and the native program is executed. The only strange thing here is that the output text isn't in my InputStream but in my ErrorStream.
    The real problem arises when I deploy the same Ear on the 9ias server. Here, the process doesn't execute my native command, terminates with error code 128 and leaves no inputStream and no errorStream.
    Errorcode 128 means that there are no child processes to wait for. (i call process.waitFor() to obtain the error code). I think this means my process isn't even started.
    Anyone familiar with processes in OC4J & 9IAS?
    Thanx in advance

    I guess your implementation of matchIp() is wrong:
    public class ReaderTest {
        public static void main(String[] args) {
            new ReaderTest().testReaderMethod();
        private void testReaderMethod() {
            ByteArrayInputStream dummyStrem = new ByteArrayInputStream(
                    ("*******************************************\n"
                            + "*   My shell Application                   *\n"
                            + "\n"
                            + "*******************************************\n"
                            + "\n" + " \n" + "\n" + "HELP: h\n" + "\n"
                            + "COMMAND: c\n" + "\n" + "QUIT:q\n" + "\n"
                            + "135.19.45.18> ").getBytes());
            System.out.println(readUntilIpMatch(dummyStrem));
        private StringBuilder buffer = new StringBuilder();
        protected String readUntilIpMatch(final InputStream in) {
            while (true) {
                try {
                    if (in.available() > 0) {
                        buffer.append((char) in.read());
                        Pattern pattern = Pattern
                                .compile("\\d{1,3}(\\.\\d{1,3}){3}(?=\\D)");
                        Matcher matcher = pattern.matcher(buffer);
                        if (matcher.find()) {
                            return matcher.group();
                } catch (final IOException e) {
                    throw new RuntimeException(
                            "Failed to read buffer in while looking for prompt!", e);
        } // runs forever if not matching!!!!
    bye
    TPD

  • Runtime.getRuntime().exec(java test)

    Hi,
    As part of a thesis for college, I am trying to execute a test java program. The program executes okay and I can read the results okay.
    Sample code.
    process = Runtime.getRuntime().exec("java test");
    InputStream iOutStream = process.getInputStream();
    InputStream ErrorStream = process.getErrorStream();
    However, I need to be able to execute a progam that reads a parameter from the screen. I tried to pass a parameter file but it doesn't work.
    process = Runtime.getRuntime().exec("java test <input.txt");
    I also tried just passing the parameters as a string array but it doesn't work either.
    process = Runtime.getRuntime().exec("java test 2, 2");
    Is there any other way that I can get the process to accept parameters?
    My deadline is looming so any help would be greatly appreciated.
    Thanks
    Eleanor
    [email protected]

    I think you are waiting when reading the output before you write to the stream until it becomes NULL or -1. That will never finish if the program you execute is expecting input!
    See a working example:
    This class does nothing than print a line on the console, then waits for a line of input, then prints the result again on the console. This is the class you'd execute from some other java code:
    import java.io.*;
    public class Input {
        public static void main(String args[]) {
            try {
                System.out.println("Before input");
                BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
                String s=r.readLine();
                System.out.println("Got line : " + s);
            } catch(Exception e) {
                    System.out.println(e.getMessage());
    }The following 'controls' the input-test class above, so compile the classes and execute the following one:
    import java.io.*;
    import java.lang.*;
    public class test {
        public static void main(String args[]) {
            try {
                Process p = Runtime.getRuntime().exec("java Input");
                BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
                BufferedWriter w = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
                String s=r.readLine(); // You cannot read until NULL because that will not happen before you have 'input' something
                System.out.println("Got: " + s);
                w.write("cvxcvxcvx\n\r");
                w.flush();
                System.out.println("waiting result:");
                while( (s=r.readLine()) != null) { // read until finished.
                    System.out.println("after : " + s);
            } catch(Exception e) {
                    System.out.println(e.getMessage());               
    }

Maybe you are looking for