Process started with java's Process.exec always returns exit code 0

1k views Asked by At

I start shell scripts with java Process.exec (for reasons), and they always return 0 exit value, regardless of exit value of script itself (which I can check by running said script in OS shell. For additional info, those scripts run gradle tasks with gradle-node-plugin. Any pointers for this issue?

Overall, setup looks as follows:

Software

  • Linux desktop 4.4.0-130-generic #156~14.04.1-Ubuntu SMP Thu Jun 14 13:51:47 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux`

  • java version "1.8.0_171" Java(TM) SE Runtime Environment (build 1.8.0_171-b11) Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)`

Shell script is executed with

Process process = Runtime.getRuntime().exec(new String[]{"sh", "-c", testScript});

Return value is obtained with test.exitValue(), and appears to be always 0.

Shell script calls gradle ./gradlew project:clean project:test.

Gradle scripts relies on gradle-node-plugin

plugins {
    id "com.moowork.node" version "1.2.0"
}

task test(type: NodeTask) {
    script = file('./node_modules/mocha/bin/mocha')
    args = ['test/sometest.js']
}
1

There are 1 answers

0
Little Santi On BEST ANSWER

Gradle scripts prevent the possibility to return the exit code to the same shell, or even ending the calling shell. This is done through the use of environment variable GRADLE_EXIT_CONSOLE (an arbitrary, non-empty value is enough):

  • If set: The script ends the shell and returns the exit code.
  • If not set: The script returns the exit code to the calling shell, allowing it to continue processing commands.

If you are calling gradle through Runtime.exec, it creates a new shell, so you need to set that variable prior to calling the script, so you get the exit code after the shell is ended.