Ruby: How do make my program trap and exit properly from a signal? - ruby

When I Ctrl C my program on linux I often get output that looks similar to a stack-dump (a crash).
Can I catch the Ctrl-C signal and exit gracefully?
Thanks!

You can trap signals with Kernel.trap:
trap('INT') do
# exit gracefully
end

Related

Basic signal communication

I have a bash script, its contents are:
function foo {
echo "Foo!"
}
function clean {
echo "exiting"
}
trap clean EXIT
trap foo SIGTERM
echo "Starting process with PID: $$"
while :
do
sleep 60
done
I execute this on a terminal with:
./my_script
And then do this on another terminal
kill -SIGTERM my_script_pid # obviously the PID is the one echoed from my_script
I would expect to see the message "Foo!" from the other terminal, but It's not working. SIGKILL works and the EXIT code is also executed.
Using Ctrl-C on the terminal my_script is running on triggers foo normally, but somehow I can't send the signal SIGTERM from another terminal to this one.
Replacing SIGTERM with any other signal doesn't change a thing (besides Ctrl-C not triggering anything, it was actually mapped to SIGUSR1 in the beginning).
It may be worth mentioning that just the signal being trapped is not working, and any other signal is having the default behaviour.
So, what am I missing? Any clues?
EDIT: I also just checked it wasn't a privilege issue (that would be weird as I'm able to send SIGKILL anyway), but it doesn't seem to be that.
Bash runs the trap only after sleep returns.
To understand why, think in C / Unix internals: While the signal is dispatched instantly to bash, the corresponding signal handler that bash has setup only does something like received_sigterm = true.
Only when sleep returns, and the wait system call which bash issued after starting the sleep process returns also, bash resumes its normal work and executes your trap (after noticing received_sigterm).
This is done this way for good reasons: Doing I/O (or generally calling into the kernel) directly from a signal handler generally results in undefined behaviour as far as I know - although I can't tell more about that.
Apart from this technical reason, there is another reason why bash doesn't run the trap instantly: This would actually undermine the fundamental semantics of the shell. Jobs (this includes pipelines) are executed strictly in a sequential manner unless you explicitly mess with background jobs.
The PID that you originally print is for the bash instance that executes your script, not for the sleep process that it is waiting on. During sleep, the signal is likely to be ignored.
If you want to see the effect that you are looking for, replace sleep with a shorter-lived process like ps.
function foo {
echo "Foo!"
}
function clean {
echo "exiting"
}
trap clean EXIT
trap foo SIGTERM
echo "Starting process with PID: $$"
while :
do
ps > /dev/null
done

How do I stop a signal from killing my Bash script?

I want an infinite loop to keep on running, and only temporarily be interrupted by a kill signal. I've tried SIGINT, SIGUSR1, SIGUSR2. All of them seem to halt the loop. I even tried SIGINFO, but that wasn't supported by Linux.
#!/bin/bash
echo $$ > /tmp/pid # Save the pid
function do_something {
echo "I am doing stuff" #let's do this now, and go back to doing the thing that is to be done over and over again.
#exit
}
while :
do
echo "This should be done over and over again, but always wait for someething else to be done in between"
trap do_something SIGINT
while `true`
do
sleep 1 #so we're waiting for that other thing.
done
done
My code runs the function once, after getting a INT signal from another script, but then never again. It halts.
EDIT: Although I accidentally put en exit at the end of the function, here on Stack Overflow, I didn't in the actual code I used. Either way, it made no difference. The solution is SIGTERM as described by Tiago.
I believe you're looking for SIGTERM:
Example:
#! /bin/bash
trap -- '' SIGINT SIGTERM
while true; do
date +%F_%T
sleep 1
done
Running this example cTRL+C won't kill it nor kill <pid> you can however kill it with kill -9 <pid>.
If you don't want CTRL+Z to interrupt use: trap -- '' SIGINT SIGTERM SIGTSTP
trap the signal, then either react to it appropriately, in the function associate with the trap, or ignore it by for example associate : as command to get executed when the signal occurs.
to trap signals, bash knows the trap command
Reset trap to former action by executing trap with signal name only.
Therefore you want to (i think that's what you say you want with "only temporarily be interrupted by a kill signal"):
trap the signal at the begin of your script: trap signal custom_action
just before you want the signal to allow interrupting your script, execute: trap signal
At the end of that phase, trap again by: signal custom_action
to specify signals, you can also use their respective signal numbers. A list of signal names is printed with the command:
trap -l
the default signal sent by kill is SIGTERM (15), unless you specify a different signal after the kill command
don't exit in your do_something function. Simply let the function return to the section in your code where it was interrupted when the signal occured.
The mentioned ":" command has another potential use in your script, if you feel thusly inclined:
while :
do
sleep 1
done
can be an alternative to "while true" - no backticks needed for that, btw.
You just want to ignore the exit status.
If you want your script to keep running and not exit, without worrying about handling traps.
(my_command) || true
The parentheses execute that command in a subshell. The true is for compatibility with set -e, if you use it. It simply overrides the status to always report a success.
See the source.
I found this question to be helpful:
How to run a command before a Bash script exits?

Thread#terminate and handling SIGTERM

Here's a simplified version of some code I wrote:
class InfiniteLoop
def run
trap('SIGTERM') do
puts 'exiting'
exit
end
loop {}
end
end
If I run:
InfiniteLoop.new.run
I can ctrl+c and get:
exiting
However, when I do this:
t = Thread.new { InfiniteLoop.new.run }
sleep 1
t.terminate
I don't see:
exiting
Can someone point me in the right direction here? I'd like to have the same behavior when terminating the thread.
If you are not sending a SIGTERM signal (via ctrl+c) the trap block is not executed.
See also the Kernel method:
at_exit { puts 'exiting' }
trap('SIGTERM') will only respond to the signals sent from OS land.
Thread#terminate is ruby code that will kill the thread.
I don't know of a way to specify behavior for a thread to take before it is killed. That might be interesting. But I don't think it exists, because the semantics of Thread#kill/terminate/join wouldn't really allow that.
Try trap("EXIT"). SIGTERM is sent by ctrl-C or a kill command. From the ruby docs:
The special signal name “EXIT” or signal number zero will be invoked just prior to program termination.

Trapping SIGINT in a backgrounded process

I am trying to understand some sample code describing signal handling in bash. In Example 32-7 at http://tldp.org/LDP/abs/html/debugging.html, the writer's comments state that he is capturing a SIGINT, yet the trap is for EXIT.
{
trap "exit" SIGUSR1
sleep $interval; sleep $interval
while true; do
...
done; } & # Start a progress bar as a background process.
pid=$!
trap "echo !; kill -USR1 $pid; wait $pid" EXIT # To handle ^C.
Why does a trap of EXIT send the correct signal (SIGUSR1) to the backgroud process on a SIGINT (Ctl-C)?
Any help is appreciated explaining why this works.
EXIT is a special handler in trap for bash, it's not a signal. There is no exit signal. This trap gets executed whenever the bash processes terminates. So, what this does is make sure that if the user kills the bash process, SIGUSR1 is sent to the background process, which also is trapped and then executes 'exit' on that process. That makes sure if you kill the session, the background process doesn't live on forever but also quits (which is probably what the comment is trying to explain).
edit: I misread this question in my original response
The EXIT pseudo-signal is raised both on normal exit and when the script is being interrupted.

Exit a Ruby script with status 0 on an exception

I'm currently wrapping scripts with begin; rescue; end. Which works, but is annoying to un/comment at two different places and so on. Is there something like error_reporting(0); in PHP, but applied to the exit code and STDERR output?
You could try trapping the EXIT signal:
The special signal name "EXIT" or signal number zero will be invoked just prior to program termination.
Something like this should guarantee that your script always returns zero to the operating system:
Signal.trap('EXIT') { exit 0 }
For example, this script:
Signal.trap('EXIT') { exit 0 }
exit 1
actually returns zero to the OS despite triggering script's termination with exit 1.
Actually I did not understand what you are asking for. Here is the answer as I understand. But would be useful if you provide some more detail.
def
some code...
rescue
abort
end

Resources