Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

share|improve this question
    
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 '11 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 '11 at 13:58
add comment

2 Answers 2

up vote 3 down vote accepted

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
share|improve this answer
    
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 '11 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. –  Dennis Williamson Feb 9 '11 at 17:10
    
will try this out. thanks too for the provided link –  ralf Feb 11 '11 at 16:04
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.