Search code examples
javabatch-filebatch-processing

Process.waitFor() returns 0 eventhough batch file being called exits with an errorcode other than 0


I'm starting a process (.bat) in java using java.lang.Process

Runtime.getRuntime().exec("cmd /c start /wait test.bat");
exitCode = process.waitFor();

The .bat process inturn calls .exe file, this .exe returns an exit code !=0 on error cases.

START /W test.exe
EXIT %ERRORLEVEL%

I want to get back the exit code returned from the batch file, but still I get back exitcode=0 always. I referred this but does not help.

Please let me know how can I get back the actual returned exit code from the process.


Solution

  • You are asking Java to launch CMD.EXE with the command start /wait test.bat which starts a second CMD.EXE process. There is EXIT %ERRORLEVEL% in the second CMD.EXE but there is no call in the scriptlet which tells the first CMD.EXE to use the status code as EXIT %ERRORLEVEL%. Thus you don't get the non-zero code of test.bat passed up to first CMD.EXE.

    The fix is easy as you don't need to use start /wait, just change the command to avoid second CMD.EXE process and then the EXIT %ERRORLEVEL% of the batch script applies to the only CMD.EXE:

    Process process = Runtime.getRuntime().exec("cmd /c test.bat");
    

    Note that Runtime is not a good way to launch sub-processes, use ProcessBuilder instead with cmd passed as String[] not String so that you don't need to escape spaces in parameters.

    Heed the warnings of the Process javadoc: failure to promptly write the input stream or read the output stream of the process may cause the process to block, or even deadlock. This means you should consume STDERR + STDOUT on different threads, or redirect STDERR to STDOUT, or redirect them to files or inherit IO streams - otherwise you may encounter problems. Many examples shown in StackOverflow won't work correctly.