This answer is applicable if you want to get the behavior of many native apps that return code 0 after a graceful shutdown.
You can register a hook that performs the graceful shutdown, for example releasing resources retained by the app. If the graceful shutdown succeeds, this hook can also override the exit code to 0. The hook will be called on SIGTERM (happens when the user is pressing Ctrl+C).
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
//graceful shutdown steps
Runtime.getRuntime().halt(0); //override the exit code to 0
}));
The solution above will prevent other hooks that may exist to run after this one. It will also prevent files to be deleted that had .deleteOnExit() called.
Another approach may be implementing and registering a SecurityManager that looks like this:
static class Converting130To0SecurityManager extends SecurityManager {
@Override
public void checkExit(int status) {
if (status == 130) {
System.exit(0);
} else {
super.checkExit(status);
}
}
@Override
public void checkPermission(Permission perm) {
// Allow all activities by default
}
}
...
System.setSecurityManager(new Converting130To0SecurityManager());
Such a security manager will always transform 130 code into 0 irrespectively of the graceful shutdown.