Runtime.getRuntime.exec() may hang?

Hi, I am trying to run a Microsoft application, suspend.exe, under Java, on xp. I noticed that sometimes the program would hang, after issuing the command.
String command = "cmd /c suspend.exe -n 15 -s 3 -l c:\\scpt\\s3.txt -e " ;
suspend = Runtime.getRuntime().exec (command);
Is there a compatibility between MS and Java after Java releases the control to the native environment? Has anyone seen this? Sometimes this gets kicked off, and sometimes it doesn't.
* I am really confused. Thanks for any help

thank you, I will look into this.
Btw, do you know how to start a java program at start up? I have searched and read some articles, but none seems to do the trick for me.
I have:
1) create a bat file. This bat file runs fine w/ double clicking, but when trying to place it in startup folder and run it, it quits.
2) create a simple c vesion of .exe file. This possesses the same behavior as above
3) create a short cut to the bat file and place it in startup folder. Nothing happens.
4) add reg. key in regedit with
'java Pclient'
and
'java c:\scpt\Pclient'
nothing seems to happen.
still searching...
thank you.

Similar Messages

  • 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() and Garbage Collection

    I am programming a piece of software in both Java and C that has some strict real time requirements. Garbage collection, which pauses all threads in Java, sometimes causes loss of incoming data. In order to get around this, I am thinking to start another process using Runtime.getRuntime().exec("c_program") and using interprocess controls (in a UNIX environment) to retrieve data from the new process.
    My only worry is that the Process created by the above call would be a child process of whatever JVM thread created it, (as far as I understand, the JVM implementation in Unix uses multiple processes) and would also be paused when garbage collection occurs. Does anyone know the implementation of the exec functionality and the JVM well enough to say that this will or will not happen?
    Thanks in advance,
    Benjamin

    You're going to create a whole new process? I don't
    know what a "child process" means, but Runtime.exec()
    gets the operating system to produce an entirely new
    process, outside the JVM. However if it produces
    output on stdout or stderr, you're going to have
    threads in your JVM that read that output, otherwise
    that process will hang.
    Why is your idea better than just calling the C
    program via JNI?Thank you both for your replies. My plan was to create a whole new process, yes. In UNIX, a process C is created by another process P using fork() or the exec() family. Process P is then the parent of process C, and process C is the child of Process P. P has an amount of control over C since it can send various signals to pause, kill, etc to C.
    My concern was that the JVM implementation would use these signals to implement the pause of all threads before garbage collecting. If it did, it may also pause the Process that it spawned from the Runtime.exec() call. Pausing my C program in this manner would cause the loss of data I was trying to avoid in the first place.
    My plan for the new process was not to produce anything on stdout or stderr, but to pass data back to the JVM using ipc (interprocess communication) resources of UNIX. I would have to use the JNI to access these resources.
    The whole reason for wanting to do this is to avoid the pause during garbage collection that all Java Threads experience. If I were just to call the C program through the JNI with a normal Java Thread as I think you were suggesting, this Java Thread would still be paused during garbage collection.
    To the second reply about RTSJ, I had heard about this but couldn't find info about it! Thanks for the link. I'm checking it out at the moment. The java runtime must be considerably different for the specifications I see that they guarantee.
    Again, thanks for the replies,
    Benjamin

  • System.getRuntime().exec() sometimes hangs on Solaris 10 u4...

    Hi everyone, I have a multi-threaded application that basically starts external programs ( bash scripts ) using Runtime.getRuntime().exec(unixCmd); The thread waits for the process to finish and when it does, returns the return code from the process. During peak period, it's not rare that the program reaches at least 5 concurrent threads, therefore 5 process are running at the same time.
    We used to run this program on Solaris 10 u2 using Java 1.5.0_6 and we never had any problem whatsoever. Recently, we moved the application to a new server running on Solaris 10 u4 using Java 1.5.0.15 and the problems started... We observed that about 1% of all the process launched hang. Even the destroy() method of the process has no effect. The only way to stop the process is with the cmd kill -9. We also observed that the script called by the application is not executed at all, not even the first line.
    Here is my code:
        Runtime shell = Runtime.getRuntime();
        Process proc = shell.exec(cmd_unix_final);
        if (Server.getProperty(PROP_LOG_ENABLED).toLowerCase().equals("true"))
          outputGobbler = new StreamGobbler(proc.getInputStream(), Server.getProperty(PROP_LOG_OUTPUT_FILE), Server.getPhase());
          errorGobbler = new StreamGobbler(proc.getErrorStream(), Server.getProperty(PROP_LOG_ERROR_FILE), Server.getPhase());
          outputGobbler.start();
          errorGobbler.start();
        do
          try
            returnValue = proc.exitValue();
            processFinished = true;
          catch (IllegalThreadStateException e)
            try { Thread.sleep(sleepInterval);}catch(InterruptedException ex){ex.printStackTrace();}
        while (System.currentTimeMillis() - launchTime < threadTimeout * 1000 * 60 && !processFinished);
        if (!processFinished)
          proc.destroy();
          returnValue = ServerReturnCodes.SERVER_RETURN_CODE_TIMEOUT_ERROR;
        return returnValue;
    ...If you have any idea what is causing the problem, please let me know, thanks!

    Thank you both for your replys. We are going to try an other version of Java soon... As for the process, the bash script does not even gets executed, the process hangs before that, at the creation phase.

  • Unable to execute Runtime.getRuntime().exec(

    Hello,
    I am new to Java programming and trying to execute (OS is Linux) an external jar File with the command:
    Runtime.getRuntime().exec("nohup java -jar SeismicAgents.jar &");It should start the SeismicAgents.jar and write the output to nohup.out.
    This works perfectly if I just enter the command at the command line.
    But upon starting it from within my program, the process seems to be started (I can see it when executin "ps aux"), but it is obviously not running as no input is written to nohup.out and the file which SeismicAgents.jar should generate is not generated.
    I also tried the following code:
    String cmd[] = {"nohup", "java", "-jar", "SeismicAgents.jar", "&"};
    Runtime.getRuntime().exec(cmd);But I am experiencing the same problem here.
    Executing something like
    Runtime.getRuntime().exec(ls);works without problems...
    Can anyone help?

    Runtime.getRuntime().exec("nohup java -jar
    SeismicAgents.jar &");Java does not interprete the '&' character. Neither does
    nohup. You would have to prefix this with /bin/sh -c, put
    the rest in quotes and, most importantly, redirect input
    and output somewhere. Without redirection, it is the task
    of your java program to feed the subprocess with input
    and drain its stdout and stderr buffers.
    Executing something like
    Runtime.getRuntime().exec(ls);works without problems...It is hard to believe this. Either it should be "ls" or
    ls is string variable containing the relevant string,
    but even then I would be surprised if you see any
    output on the command line. At least I don't get
    anything with public class bla {
      public static void main(String[] argv) throws Exception {
        Runtime.getRuntime().exec("ls");
    }If you don't want a "/bin/sh -c" hack, you may want to
    try http://www.ebi.ac.uk/~kirsch/monq-doc/monq/stuff/Exec.html .
    Harald.

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

  • 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("cmd /c start file\\"+"My file.txt" ) Not work

    Hello
    i have a problem I use:
    Runtime.getRuntime().exec("cmd /c start file\\"+"My file.txt");
    to open "my file.txt" And I have error System Windows don't open file file\My becaus file My don't exist When I rename file to "Myfile.txt" and use:
    Runtime.getRuntime().exec("cmd /c start file\\"+"Myfile.txt");
    It's work great. My problem is when my file have space in name or other [ ], etc symbol. How fix this problem?
    Thenks to help:)

    Try using the verson where you specify the parameters in an array as this example shows:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=635363
    Note: you may need to enclose the file name in quotes

  • Weird behaviour with Runtime.getRuntime.exec() attempting to start IE

    I have developed a sample scheduler that it a web page the user fill in and then create a process schedule by the Timer class. The process starts IE in order to automate data entry normally done by a user. The Java code run well but IE when start from the p = Runtime.getRuntime().exec() class freeze. Is anyone can tell if IE require special setting to run in background?
    Here the Java code but once again it work well but IE freeze and cause the forked process to hang.
    // The schedule task
    public void scheduleTask(Object o) throws ApplicationException {
    ScheduleBean sb = (ScheduleBean)o;
    try {
    Timer timer = new Timer(true);
    RunReslotting rr = new RunReslotting();
    timer.schedule(rr, sb.getSchedulingDate());
    catch(IllegalArgumentException iae) {
    throw new ApplicationException(iae.getMessage());
    catch(IllegalStateException ise) {
    throw new ApplicationException(ise.getMessage());
    public class RunReslotting extends TimerTask {
    protected RunReslotting() {
    public void run() {
    String[] cmdLineParam = transportProfile(2);
    cmdLineParam[0] = "location=" + wr.getLocation();
    cmdLineParam[1] = "loc_class=" + wr.getNewStrategy();
    forkProcess("runie.bat", cmdLineParam);
    private String[] transportProfile(int startAt) {
    envProf = System.getenv();
    profCmd = new String[envProf.size() + startAt];
    itr = envProf.entrySet().iterator();
    int i = startAt;
    while (itr.hasNext()) {
    entry = (Map.Entry)itr.next();
    profCmd[i] = (String)entry.getKey() + "=" + (String)entry.getValue();
    i++;
    return profCmd;
    private void forkProcess(String processName, String[] osParam) throws ApplicationException {
    // Lance un nouveau process
    p = null;
    int i=0;
    try {
    p = Runtime.getRuntime().exec(processName, osParam);
    // Vide les buffers du process pour eviter de geler
    mcError = new MessageCatcher(p.getErrorStream());
    mcOutput = new MessageCatcher(p.getInputStream());
    mcError.start();
    mcOutput.start();
    i = p.waitFor();
    if ( (i != 0) || (mcError.getMessage() != null) || (mcOutput.getMessage() != null) ) {
    System.err.println("*** Process failed RC:" + i + " *** ");
    if (mcOutput.getMessage() != null) {
    System.err.println("Output messages: " + mcOutput.getMessage());
    if (mcError.getMessage() != null) {
    System.err.println("Error messages: " + mcError.getMessage());
    throw new ApplicationException("*** Process failed *** ");
    catch(IOException ioe) {
    throw new ApplicationException(ioe.getMessage());
    catch(InterruptedException ie) {
    throw new ApplicationException(ie.getMessage());
    Any suggestion will be appreciate. I�m working on that scheduler for a while and i'm desperate
    Thanks
    Francis

    This starts IE for me, no problem
    String[] cmd = {"C:\\Program Files\\Internet Explorer\\iexplore.exe"};
    Runtime.getRuntime().exec(cmd);

  • How to execute an application in Solaris using Runtime.getRuntime.exec() ?

    I am currently doing a project which requires the execution of Solaris applications through the use of Java Servlet with this Runtime method - Runtime.getRuntime.exec()
    This means that if the client PC tries to access the servlet in the server PC, an application is supposed to be executed and launched on the server PC itself. Actually, the servlet part is not an issue as the main problem is the executing of applications in different platforms which is a big headache.
    When I tried running this program on a Windows 2000 machine, it works perfectly fine. However, when I tried it on a Solaris machine, nothing happens. And I mean nothing... no errors, no nothing. I really don't know what's wrong.
    Here's the code.
    public void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
         response.setContentType("text/html");
         PrintWriter out = response.getWriter();
              Process process;                                                       Runtime runtime = Runtime.getRuntime();
              String com= "sh /opt/home/acrobat/";
              String program = request.getParameter("program");
              try
                        process = runtime.exec(com);
              catch (Exception e)
                   out.println(e);
    It works under Windows when com = "c:\winnt\system32\notepad.exe"
    When under Solaris, I have tried everything possible. For example, the launching of the application acrobat.
    com = "/opt/home/acrobat"
    com = "sh /opt/home/acrobat"I have also tried reading in the process and then printing it out. It doesn't work either. It only works when excuting commands like 'ls'
    BufferedReader read = new BufferedReader(new InputStreamReader(process.getInputStream()));Why is it such a breeze to execute prgrams under Windows while there are so many problems under Solaris.
    Can some experts please please PLEASE point out the errors and give me some advice and help to make this program work under Solaris! Please... I really need to do this!!
    My email address - [email protected]
    I appreciate it.
    By the way, I'm coding and compiling in a Windows 2000 machine before ftp'ing the .class file to the Solaris server machine to run.

    it is possible that you are trying to run a program that is going to display a window on an X server, but you have not specified a display. You specifiy a display by setting the DISPLAY environment variable eg.
    setenv DISPLAY 10.0.0.1:0
    To check that runtime.exec is working you should try to run a program that does not reqire access to an X Server. Try something like
    cmd = "sh -c 'ls -l > ~/testlist.lst'";
    alternatively try this
    cmd = "sh -c 'export DISPLAY=127.0.0.1:0;xterm '"
    you will also need to permit access to the X server using the xhost + command

  • 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

  • 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...)

  • Runtime.getRuntime.exec() not working when Tomcat is made a windows Sevice

    Hi,
    I am working on a web application which launches a exe file on subitting the form. I am using Apache Tomcat 4.0.6 to run the web application. Initially Tomcat was not made a windows service on my machine and when I launch an exe it is launching without any problems. I used the following command to launch the exe file:
    <code>
    Process p = Runtime.getRuntime().exec("C:\\Program Files\\Mercury Interactive\\WinRunner\\arch\\wrun.exe" + strWROptions);
    </code>
    The above command launches WinRunner on the local machine.
    without using tomcat if I just compile and run a test program with this command, the exe is launching perfectly. But, Once I made tomcat a windows service on my machine the exe is not launching.
    Also, a process is being created in the windows task bar named wrun.exe once I submit the form but WinRunner is not lauching on the desktop.
    Can any one please help and suggest me.
    Thanks,
    Ramesh

    The version of Java I am using is 1.4.2. Even without
    using the string array as you mentioned, the exe
    (wrun.exe) is launched on my desktop if I don't run
    Tomcat as a windows service. But the problem arises on
    making it a service :-(
    That is strange because going by the documentation what you have been using should never work. I can't test it though, I'm not on MSWindows at the moment..
    Now, when I use this string array convention, I am
    getting an error saying "The tool could not launch..
    some error occured".
    That's not a Java error message, it must come from WinRunner. This means that you have succesfully started WinRunner (great!) but something else is wrong; maybe the parameters you pass to it are incorrect.
    How would you run it on the command line? Like this?wrun -t "D:\L5_QE\L5A\Initial" -create_text_report on -runThat line executes the wrun program and passes it five parameters, not three. The first parameter is "-t", the second "D:\L5_QE\L5A\Initial", the third "-create_text_report", the fourth "on", and the fifth "-run". The array of strings that corresponds to that line isString[] command = {"C:\\Program Files\\Mercury Interactive\\WinRunner\\arch\\wrun.exe",
                    "-t", "D:\\L5_QE\\L5A\\Initial",
                    "-create_text_report", "on",
                    "-run"};

  • 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

Maybe you are looking for

  • Can you listen for a string value to change?

    Is there any easy way to see if a string changes value? I have a public static string in one instance of a class that I wish to be notified when it changes. An object of another class will have the listener. Edited by: sarcasteak on Dec 8, 2009 1:40

  • Price Condition Depending of Material Master Record

    Helllo Experts, I have an issue with a price condition on a price procedure  the user wants to be able to mantain the price condition manually only if the material used at item level of sales order is equal to one of 3 sku´s. This Price condition can

  • Open attachments in compatible third-party apps.

    I have I-phone 32 GS and I upgrade to IOS 4 Can any one adv me how to open attachments in compatible third-party apps. my emails are MFE

  • Itunes recognizes iphones as cameras.  How to I get back to opening the phone with itunes?

    My computer will not recognize my iphone as an iphone. It recognizes it as a camera.  itunes also does not recognize the iphone.  How do I redirect the comptuer to opent the phone with itunes?

  • Find Open Deliveries for Material

    Hi, I have to check if a specified material has an Open Delivery or not. The only import parameters I can use is Plant, Storage Location and Material Number. Is there any Bapi that can check if there is an Open Delivery for that material? Thanks, Den