Mouhammed Soueidane
Mouhammed Soueidane

Reputation: 1066

Get exit code from a java application in batch file

I'm currently making an effort to create test cases for one of our java applications. In my code, my java application calls a batch file, which in turn starts a separate java process, that returns an error code that I need to consume from the calling java application. I'm doing the following to invoke my batch file:

Process process = runTime.exec(new String[]{"cmd.exe","/c",scriptPath});
exitValue = process.waitFor();

The batch file is as follows:

@echo off
cd %~dp0
java -cp  frames.FrameDriver
SET exitcode=%errorlevel%
exit /B %exitcode%

Now with the above code and batch file, my JUnit framework just hangs on this particular test case, as if it's waiting for it to end. Now when JUnit is hanging on the test case, going to the Task Manager, and ending the java.exe process would allow the JUnit framework to continue with the other cases.

Running the .bat file by double clicking it runs the Java application normally.

Adding the START batch command before the java command in my batch file seems to fix the hanging problem, but I can't seem to get the correct exit code from my Java application as it's always 0. (The Java application exits with an error code using System.exit(INTEGER_VALUE)). I'm assuming that the %errorlevel% value is being overwritten by the "start" command's own exit value.

Can anyone please tell me how to solve this problem?

Thanks.

P.S: If it makes any difference, I'm using JDK 5 and Netbeans 5.5.1.

Upvotes: 3

Views: 9614

Answers (1)

djangofan
djangofan

Reputation: 29669

Don't use the /B on your exit. Here is how I would do a script:

@ECHO off
ECHO Running %~nx0 in %~dp0
CALL :myfunction World
java.exe -cp  frames.FrameDriver
IF NOT ERRORLEVEL 0 (
  SET exitcode=1
) ELSE (
  SET exitcode=0
)
GOTO :END
:myfunction
ECHO Hello %~1
EXIT /B 0
:END
EXIT %exitcode%

NOTE: Also, you can execute java program in 3 different ways:

  java.exe -cp  frames.FrameDriver
  CALL java.exe -cp  frames.FrameDriver
  cmd.exe /c java.exe -cp  frames.FrameDriver

This is very critical since, your Java command may exit with a exit code and in order to pass the exit code correctly to the ERRORLEVEL var, you need to use the correct method above, which I am unsure about.

Upvotes: 3

Related Questions