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

Similar Messages

  • Tidal abends with error message: Jvm call Runtime.exec() returned null

    just wandering if this error "Jvm call Runtime.exec() returned null  Command[chmod 777] launch failed." is a tidal error and not a job command error returned from the OS server.
    thanks,
    warren

    I'm having the same problem...
    Have you been able to solve your problem yet?

  • Runtime.exec() - how to open new window for new program?

    Hi,
    I have searched through the forums but haven't found an answer to this one yet. I am using runtime.exec() to start up a new java program. At first I thought it wasn't running properly but, after checking task manager, I have discovered that the new program I open runs, it is just completely invisible to me. I am wondering how I can get the new program to run in a command window or something where I can monitor it.
    Thank you for your help,
    Drew

    Thank you all. After trying to figure out why the start command wouldn't work in the runtime.exec() call(not an executable - I am a dolt), I tried putting it in a batch file and it worked perfectly. Thanks for your help,
    Drew

  • Runtime.exec() on RedHat Linux

    Guys
    Like many before me, it seems, I've having a nightmare with Runtime.exec() across platforms when executing local files.
    I've gone for the basic but robust strategy of writing the required function to a local file and then executing the file. This has worked fine on Windows NT/2000 and on Solaris. But RedHat Linux doesn't want to know.
    I know my permissions are good to execute. I can create the file then run it at the command line, but then whenever I go to run from within Java I get an exit value of 255.
    An old chestnut, I know. But can anyone offer an help?
    Cheers
    Dom

    Here's a small class & main method that illustrates the problem.
    The output I get is:
    File path: /tmp/Temp26345.sh
    chmod +x exit value: 0
    Executing file: 255
    I can then go into /tmp and run ./Temp26345.sh at the command line and get the "ls" command to run.
    import java.io.*;
    public class FileExecutor
         public static void main( String[] args )
              if( args.length == 0 )
                   System.out.println("Arguments must be given: [filename] [writeable]");
                   return;
              try
                   FileExecutor fe = new FileExecutor();
                   File executable = fe.createFile( args[0] , args[1] );
                   fe.executeFile( executable );
              catch( Throwable t )
                   t.printStackTrace();
         public File createFile( String fileName , String contents )
              throws IOException
              //Create the file.
              File tempFile = File.createTempFile( fileName , ".sh" );
              //Write to the file.
              FileOutputStream fos = new FileOutputStream( tempFile );
              OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" );
              int length = contents.length();
              osw.write( contents , 0 , length );
              osw.flush();
              osw.close();
              fos.close();
              return tempFile;
         public void executeFile( File file )
              throws InterruptedException , IOException
              String filePath = file.getAbsolutePath();
              System.out.println( "File path: " + filePath );
              Runtime runtime = Runtime.getRuntime();
              //Actual system permission.     
              Process process_perm = runtime.exec( "chmod +x " + filePath );
              int exitValue = process_perm.waitFor();
              System.out.println( "chmod +x exit value: " + exitValue );
              //Execute the file.
              Process process_exec = runtime.exec( filePath );
              exitValue = process_exec.waitFor();
              System.out.println( "Executing file: " + exitValue );

  • IOException File not found - While using Runtime.exec

    Hey All,
    I have written a Java application which needs to start up another external application. I have executables for that external application for different platforms (Win32, PPC and Linux). When the Java application is started it detects the OS and starts up the right executable according to the OS. The executable loads up fine on Windows without any problems. But in both Linux and Max OS X I get this exception:
    java.io.IOException: java.io.IOException: "/home/vilas/Documents/Project/build/CLISP/linux/lisp.run": not found
            at java.lang.UNIXProcess.<init>(UNIXProcess.java:143)
            at java.lang.Runtime.execInternal(Native Method)
            at java.lang.Runtime.exec(Runtime.java:566)
            at java.lang.Runtime.exec(Runtime.java:428)
            at jplan.communication.lispserver.LispServer.startupServer(LispServer.java:143)
            at jplan.communication.lispserver.LispServer.run(LispServer.java:109)
            at java.lang.Thread.run(Thread.java:534)lisp.run has all the necessary permissions. If I copy the string (/home/vilas/Documents/Project/build/CLISP/linux/lisp.run) and paste it in a terminal and press enter, the application starts up fine without any problems!! Can you please tell me what could be going wrong?
    The following extra information maybe helpfull:
    1) I use the exec(String command, String[] envp, File dir) version of exec.
    2) The complete format of the command is as follows (one long string):
    "/home/vilas/Documents/Project/build/CLISP/linux/lisp.run" -B "/home/vilas/Documents/Project/build/CLISP/linux" -M "/home/vilas/Documents/Project/build/CLISP/linux/lispinit.mem" -i loader.lisp
    Thanks in advance for your time and efforts.

    I found the problem after extensively searing the forums (looking upto page 4 !! of the results). The problem was that I was using quotes to surround the paths in the command. If you copy and paste it in a terminal it will work fine but it does not work with runtime.exec. I am not sure, but I think the reason is that when a terminal is used, some pre-processing of the commands take place before they are passed onto the OS(shell). But while using runtime.exec, that pre-processing is not peformed and therefore some things will not work.
    In order to fix the problem, I use quotes only when the OS is windows. In other cases(OS X, Linux) I escape the spaces i.e. replace " " with "\ ".
    PS: The executable is a binary compiled from C code.

  • 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 not releasing lock on files

    Hi,
    I am using Runtime.exec to launch an external application, a batch file that runs a java program and generates a pdf file on disk. The Runtime.exec is called from inside the callback function of a toolbar button in my UI. Once, the runtime.exec returns, I popup a alert saying "pdf generated successfully". However, when I try to open the pdf that has been generated, I get a message saying the "program is in use by another program" or some such message. Only when I quit my GUI application, Iam able to open the pdf file using acrobat reader.
    Can someone tell me how to solve this problem. I have tried doing proc.waitFor() etc.
    Cheers,
    vidyut

    You can try some of sysinternals tools to look through file sharing information and decide what process is locked file.
    PS Try to ensure that you start java in same process as batch file executes, overthise you just can't ensure it terminates on time.

  • Issue using Runtime.exec() in Vista

    I've coded a simple method using Runtime.exec() to get the client MAC ID , and it worked alright on XP. Now my client want to switch to vista , and the method is not working. Here's my code
    import java.io.*;
    import java.util.regex.*;
    public class GetMac
         public static String getMacAddress()
              String mac="";
              System.out.println("getMacAddress");
              try {
                   RunTimeExecutor re=new RunTimeExecutor("ipconfig /all");
                    mac=re.executeAndReturnMac();
                    re.destroy();
              } catch (Exception e) {
                   e.printStackTrace();
              return mac;
    import java.io.IOException;
    import java.io.InputStream;
    * @author amal
    public class RunTimeExecutor
              String cmd;
              Process proc;
               * @param cmd
              public RunTimeExecutor(String cmd)
                        this.cmd=cmd;
               * @return boolean
               * @throws WIException
              public  String executeAndReturnMac() throws Exception
                   System.out.println("run");
                   String mac="";
                        if(cmd==null)
                                  throw new Exception("No Commands");
                        try
                              final Runtime rt = Runtime.getRuntime();
                              proc = rt.exec(cmd);
                              final StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream());
                              InputStream iis=proc.getInputStream();
                              final StreamGobbler outputGobbler = new StreamGobbler(iis);
                              errorGobbler.start();
                              outputGobbler.start();
                              int exit=proc.waitFor();
                              System.out.println("exitVAl "+exit);
                              if(exit==0)
                                   mac=outputGobbler.MAC;
                              return (exit==0) ? mac :null;
                    catch (IOException e)
                              e.printStackTrace();
                    catch (InterruptedException e)
                              e.printStackTrace();
                    catch(Exception e)
                         e.printStackTrace();
                    return null;
              public void destroy()
                        if(proc!=null )
                                  proc.destroy();
    * @author amal
    import java.io.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    * @author amal
    public class StreamGobbler extends Thread
        InputStream is;
        OutputStream os;
        public String MAC;
        StreamGobbler(InputStream is)
            this(is,null);
        StreamGobbler(InputStream is,OutputStream redirectTo)
            this.is = is;
            this.os = redirectTo;
         * @see java.lang.Thread#run()
        public void run()
            try
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
                InputStreamReader isr = new InputStreamReader(is);
                int c=0;
                BufferedReader br = new BufferedReader(isr);
                String line=null;
    System.out.println("Start Reading");
                     while ( (line = br.readLine()) != null)
                          System.out.println(line);
                         if (pw != null)
                             pw.println(line);
                         Pattern p = Pattern.compile(".*Physical Address.*: (.*)");
                            Matcher m = p.matcher(line);
                            if (m.matches())
                                 MAC = m.group(1);
                                 System.out.println("seting MAC to "+MAC);
                                 break;
                if (pw != null)
                    pw.flush();
            } catch (Exception e)
                e.printStackTrace(); 
    }The inputStream of the process doesnt get printed at all , the loop condition in StreamGobbler 'while ( (line = br.readLine()) != null)
    ' is never true.
    Also , in random cases i've seen the System.out.println("exitVAl "+exit); line executing before the System.out.println("Start Reading"); line , and i though proc.waitFor() would guarentee otherwise.

    thx guys for ur replies . The issue was because of some browser security system ( or so they said . ).However i'm still puzzled about the 'waiting for the stream to finish' part .
    paul.miner wrote:
    {I think the process is allowed to end with output still in the >>buffers, ..so this would be expected. You should be waiting for >>your .streams to finish, since that's what you really >>care .about. .Also, .you need to add synchronization between your >>threads so you can accurately retrieve "MAC". Also, do not break out >>of the loop when you find what you're looking for, you should >>continue .reading until the end of the stream.Wasn't I suppose to be reading out of the stream to prevent an overflow?Also the break is done there are multiple lines like 'Physical address .....: xxxxxxxxxx ' in the output , and the macid is the first one.About the ProcessBuilder , I'll look into it . Thx for your advice.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Runtime.exec() process output

    I am having strange problems with the output from a program I am executing with Runtime.exec(). This program takes voice input, and generates text output on the commandline. For some reason, I do not see any of the output until the program exits, then everything is displayed. My code is below, any help would be greatly appreciated!
    Thanks,
    Deena
    import java.io.*;
    import java.util.*;
    //Reads and prints the output streams from an executing process
    class ProcessStream extends Thread{
         InputStream is;
         String type;
         ProcessStream(InputStream is, String type){
         this.is = is;
         this.type = type;     //type of output stream, e.g. stdout or stderr
         public void run(){
         try{
              BufferedReader br = new BufferedReader(new InputStreamReader(is));
              String line=null;
                   //read and display the output stream of an executing process
              while ((line = br.readLine()) != null){
              System.out.println(type + ">" + line);
         } catch (IOException ioe){
         System.err.println(ioe);
    //Interface to TalkBack.exe
    public class JTalkBack{
         public static void main(String[] args){
         try{
              String arg="TalkBack.exe -noTTS -noReplay";     //program to execute
              //arguments to program
              for(int i=0; i<args.length; i++){
                   arg+=" "+args;
              //execute the program and get an object representing the process
              Process p=Runtime.getRuntime().exec(arg);
              //create stream processors for stdout and stderr of the process
              ProcessStream error = new ProcessStream(p.getErrorStream(), "ERROR");
              ProcessStream output = new ProcessStream(p.getInputStream(), "OUTPUT");
              //start the stream processors
              error.start();
              output.start();
              //wait for the process to finish and get its exit value
              int exitVal = p.waitFor();
         System.out.println("ExitValue: " + exitVal);
         catch (Throwable t){
         System.err.println(t);

    I have something similar and it works. The only difference is that I:
    1. used a BufferedInputStream instead of the BufferedReader, which means bis.available() and bis.read(buffer) were used instead of .readLine(bis)
    2. Didn't print to stdout, but instead fired a proprietary MessageEvent with the string in it to all MessageListeners (good for use with java.util.logging)
    3. Didn't (yet) put the input streams in different threads.
    Maybe it is related to the fact that you are printing directly back to the System.out again? Does each process in Java get its very own standard out? I don't know.
    It's ugly and convoluted, but maybe a snippet of my code will help...
    (in run)
    Thread myThread = Thread.currentThread();
      try {
        proc = r.exec("my_secret_process.exe -arg arg");
        is = new BufferedInputStream(proc.getInputStream());
        while (thread == myThread) {
          int iRead = 0; //how many bytes did we read?
          //message stream check
          if(is.available() > 0) {
            iRead = is.read(buf);
            msg = "\n"+new String(buf, 0, iRead);
            this.fireMessageArrived(new MessageEvent(this, msg));
         } //end while
       } catch(Exception e) {
          System.out.println("Argh.  Barf.");
      Tarabyte :)

  • Runtime exec problem with command "start"

    L.S,
    I'm working on a webservice client for uploading
    and downloading files. When a file is downloaded, it
    should be opened by the appropriate application. I
    know that this is -in theory- possible by issuing a
    start command through Runtime.getRuntime.exec():
    public void doSomething(String realName, DataHandler handler) {
      File outFile = new File(realName);
      FileOutputStream out = new FileOutputStream(outFile);
      handler.writeTo(out);
      out.close();
      String fileName = outFile.getAbsolutePath();
      Process p = Runtime.getRuntime().exec("start " + fileName);
    }Running this on my Win2000 system with J2RE 1.4.2 consistently
    fails with this message:
    java.io.IOException: CreateProcess: start C:\tmp\test.pdf error=2When I issue the exact same command from a DOS shell, Adobe
    starts up with the test document loaded. I now believe that my own
    application is somehow 'holding on to' the file, preventing an
    external application like Adobe from consuming the same file.
    Does anyone know how I can get around a problem like this? How do
    I start the appropriate application and feed it the file that was
    just downloaded by the user?

    I did a search for Runtime.exec and found some good help in this forum. Someone posted something like the following and it works pretty well.
    <<begin code>
    // Determine proper shell command (extend per OS)
    String os_name = System.getProperty("os.name");
    String shellParam "";
    if (os_name.startsWith("Windows"))
    if ( (System.getProperty("os.name").endsWith("NT")) ||
    (System.getProperty("os.name").endsWith("2000")) ||
    (System.getProperty("os.name").endsWith("XP")) )
    shell = "cmd.exe";
    } else
    shell = "command.com";
    shellParam = "/C";
    // Create a string with your program executable
    String command = "myprogram.exe";
    // Create an array of each command, I found that placing "cmd.exe /c"
    // in the same string doesn't work.
    String[] cmd_array = new String[] {
    shell,
    shellParam,
    command
    Runtime.getRuntime().exec( cmd_array );
    <<end code>>
    Do a java API search for Runtime.exec (if you use Eclipse right click and hit Open Declaration) there are ways to invoke exec that support setting of the environment as well as the current directory.

  • Runtime.exec() - Strips the parameter list on encountering  a newline(\n)

    I am executing a batch file from Runtime.exec() and i am passing a list of parameters to the batch file in the form of name=value pairs.One of the parameters value is a multiline text containing "\n" characters.i.e input from a textarea.
    When my program executes the batch file it prints all the parameters till it encounters the "\n" character and strips all the remianing parameters.And it does not show any error .
    Is this a bug of Runtime.exec method ?
    If not, how to resolve this problem?

    Bug in Runtime.exec? Nope, it's probably you and your code.
    Read this - everyone who uses Runtime.exec should:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Runtime.exec command with spaces

    I'm having problems using exec on (unix) commands that take filenames as a parameter - eg chmod.
    The problem is that I've been blessed with some filenames which contain spaces and I can't figure out a way to pass these through.
    The code I'm trying is :
    String fs="/";
    String droot="home";
    String fname="tom test";
    String fullFileName=fs + droot + fs + fname;
    String outlist[] = runCommand("chmod 777 " + fullFileName );
    if fname contains no spaces, then this will work fine, but (as in the example above) if it contains a space, then I get an error (can't find files).
    Any ideas?
    Thanks
    Tom

    The reason that putting quotes around the filename works on the command line is that they affect how the command line interprets them.
    However, Runtime.exec does not intepret the quotes as special characters. If you have a space in an argument, you should use the Runtime.exec method that takes a String[] argument, and place each argument in an array element.

  • Supressing windows spawned from Runtime.exec()

    Hi,
    I was wondering if anyone had any suggestions on how to suppress windows spawned from using Runtime.exec(program). I've had a good look at the Process object returned from this and cant find a way to do it. I'd like to keep the process being run completely invisible from the user but i'm getting a blank window appear - spawned from the app being run.
    Any ideas?
    TIA,
    Danny

    The exec is called k.exe - its a programming language. I'm writing an interface for a database system called KDB which is implemented in K. (called using 'k db args...').
    Have a look at www.kudib.com if you want to see a bit more about my project or www.kx.com to learn more about K and KDB.
    Danny

  • Return from Runtime.exec()

    Hello all,
    I am executing a Windows 2000 command using Runtime.exec() which establishes a connection using "rasdial" to a remote server. However the exec method returns immediately, before the "rasdial" command has had a chance to complete. Does anyone know of a method which executes an OS command but waits for the command to finish before returning? Something like System would be ideal.
    Any help is appreciated,
    Regards,
    Jason

    In Java version 1.3 (and later) method exec() of class Runtime returns a Process instance when invoked. The process object returned is what you need to manage.

  • Runtime exec opens new window

    Hi, I am using Runtime.exec to run an external application in Windows2000. � can read its output and i can destroy it without any problems.
    But when i run my java application with javaw , the external application i run with rt.exec opens new window(without output texts, empty) . just output command windows which opens when i run the external app. from a command prompt.
    If i run my java application with java.exe then then external application DO NOT open new window and run correctly. But this time my java window stays on desktop, and that's not any good for a Windows Application.
    In both cases everything runs OK. The only problem is the command prompt windows.
    Is there a solution when working with javaw.exe ? or hide the window when running with java.exe
    Thanks all.

    bug with ID: 4244515

Maybe you are looking for

  • Select table columns dynamically at runtime

    Hi All, I've the requirement where user wants to see report columns based on certain parameters. Report contains revenue data for range of periods for a transaction, and each period is a column in table (period starting from 01-JAN-2010 to 31-DEC-202

  • Plug-in PDF, Internet Explorer, unable to open a pdf file from web site. Question mark

    Hello, A computer where Acrobat 9 Standard and Acrobat Reader 9 have been installed. When I try to read a pdf file from a web site and read it in IE, I get a popup whith a question mark and no text. The pdf file is not open. I have try to reinstall t

  • HP Photosmart P1100 won't feed, rollers not turning, tried all recommended solutions.

    All other functions appear to be working normally. Here are the symptoms when I use the print test page function: The print head moves back and forth making all the regular sounds when it prints a first page but no paper is feed. The rollers never tu

  • Error FAGL_SKF008 when loading data from 0FI_GL_8 infosource

    Hi, I am loading data into an infocube, from 0FI_GL_8 infosource. We have connected ECC-P with BI-D and BI-P. When loading data into BI-D works Ok, but when loading data into BI-P, the next error message appears: "No authorization for displaying stat

  • Windows keyboard layouts on Arch

    Hi everyone, I always wanted a Dvorak keyboard, so I swapped the keys in mine to get an italian Dvorak keyboard, the iDvorak. Unfortunately Linux doesn't natively support this layout and the iDvorak team only released a Windows version. I have the DL