How can I use SIGUSR1 or SIGUSR2 without risk of terminating the process?
SIGUSR1 and SIGUSR2 are user-defined signals. Imagine there is a tool designed to do something useful upon receiving one or the other.
The problem is the default action for these signals is
man 7 signal), so it's safe to send SIGUSR1 or SIGUSR2 to the tool only after it started handling (or ignoring, or blocking) the signal. Send it too soon and the process will be terminated.
Personally I'm surprised by this default behavior. When I want to use SIGUSR1 or SIGUSR2, it's because there is (or I hope there is) a handler that does something useful. In no case I want the signal to terminate the process. If I wanted to terminate the process, I would simply generate SIGTERM.
Our example tool can be GNU
dd. If it manages to set things up then it will react to SIGUSR1 by printing I/O statistics to its stderr. But try this:
dd if=/dev/zero of=/dev/null & kill -s USR1 "$!"; sleep 1; kill -s USR1 "$!"; sleep 1; kill "$!"
Most likely you will see
dd terminated by SIGUSR1 generated by the first
kill. The second and the third
kill will tell you there is
no such process.
sleep 1 before the first
kill then you most likely give
dd enough time to set things up and each
kill will work as intended:
dd if=/dev/zero of=/dev/null & sleep 1; kill -s USR1 "$!"; sleep 1; kill -s USR1 "$!"; sleep 1; kill "$!"
But this is not a firm method, as there is no guarantee
sleep 1 is enough. In theory no interval is long enough.
How can I use SIGUSR1 or SIGUSR2 without any risk of terminating the process?