Gradle task: start a service
task startService(type: Exec) {
standardOutput = new ByteArrayOutputStream()
errorOutput = new ByteArrayOutputStream()
commandLine 'cmd', '/c', 'net', 'start', 'serviceFoo'
doLast {
println standardOutput.toString()
println errorOutput.toString()
}
}
running "net start serviceFoo" will print "access denied" message on windows.
but gradle startService, no message is printed.
tried it on Windows command prompt (admin):
commandLine 'net', 'start', 'serviceFoo'
Error message:
* What went wrong:
Execution failed for task ':startService'.
> Process 'command 'net'' finished with non-zero exit value 2
On command prompt (admin):
net start serviceFoo
Successful.
Gradle will by default throw an exception and terminate when receiving non-zero result codes from commands. You can disable this by setting the property
ignoreExitValue true
in your task. Normally you'd also wanna check for it yourself then, eg.
doLast {
if (execResult.getExitValue() != 0) {
...
}
}
Here is what I am using for newer version of gradle:
task myCommandLineTask(type: Exec) {
commandLine 'my_command.sh'
ignoreExitValue = true
standardOutput = new ByteArrayOutputStream()
doLast {
def exitCode = executionResult.get().exitValue
if (exitCode != 0) {
def result = standardOutput.toString()
println result
throw new GradleException("Failed to run command (exit code:$exitCode)")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With