Is it possible to enforce a certain exit code when using "kill" to stop a process?
-
do you mean that you want the program to be killed returning a certain code? or you want to send a certain type of signal by using kill? or that in your custom application, when a user sends a kill signal, you perform some action?– g19fanaticFeb 9, 2011 at 12:14
-
i mean the first option you mention, i.e. force the program to be killed return a certain code. sorry for not being clear enough– ralfFeb 9, 2011 at 13:58
3 Answers
This will exit with a 42 if any of the listed signals are received. You could perform other actions including calling a function, etc.
#!/bin/bash
trap 'exit 42' SIGINT SIGQUIT SIGTERM
-
1this does not quite solve my problem. probabely it makes sense to step out a bit and explain what i am trying to do: i have a shell script that starts a process, and in case the process exits with code 0, restarts it. now in some cases i want to restart the process manually i which case it would be nice to just call 'kill PID'. however, kill does not necessarily return with code 0. it would be nice to enforce this. does this make sense to you?– ralfFeb 9, 2011 at 17:03
-
@ralf: Would
(kill PID; exit 0)
(doing the kill in a subshell with an unconditionalexit 0
) work for you? The only timekill
should return non-zero is if there's an error (e.g. no such process or invalid option). You should also take a look at Process Management. Feb 9, 2011 at 17:10 -
Yes, you have the trap the kill signals you send to your script using the trap command, see man bash and look for the trap command.
After "trapping" the signal sent to the script, you could exit with any value you want to.
Just a quick clone from that accepted answer if you want to continue afterwards:
trap 'true' SIGINT SIGQUIT SIGTERM EXIT
[ $DO_RESTART -eq 1 ] && pkill netdata || true
echo afterwards