the built-in Gradle javaexec doesn’t return a handle, as it is blocking. Depending on what control you have over the external process, you could:
a) Launch the javaexec via a shared build service that wraps this in an Executor to make it async;
b) At the end of the build, ask the external process to stop. If you can have the external process look for “.stopfile” or somesuch and kill itself.
…if that flow isn’t possible, a variation:
a) as above, but launch the process yourself instead of with JavaExec to retain a handle;
b) at the end of the build, ask the shared service to shutdown external processes (that you now have a handle to)
Other variations, such as using the OS to ‘kill’ a PID, may be possible (assuming you can get the PID).