Get exit code from a java application in batch file

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 21:13:35

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/15136708/get-exit-code-from-a-java-application-in-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!