8

Is it possible to enforce a certain exit code when using "kill" to stop a process?

2
  • 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?
    – g19fanatic
    Feb 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
    – ralf
    Feb 9, 2011 at 13:58

3 Answers 3

3

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
3
  • 1
    this 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?
    – ralf
    Feb 9, 2011 at 17:03
  • @ralf: Would (kill PID; exit 0) (doing the kill in a subshell with an unconditional exit 0) work for you? The only time kill 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
  • will try this out. thanks too for the provided link
    – ralf
    Feb 11, 2011 at 16:04
2

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.

0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .