Bash – Set Up Signal Trap for SIG_IGN and SIG_DFL

bashlinuxsignals

From https://unix.stackexchange.com/a/447032/674

So in terms of code, assuming the SIGINT signal, these are the three
options:

  • signal(SIGINT, SIG_IGN); to ignore
  • To not call the signal() function, or to call it with signal(SIGINT, SIG_DFL); and thus to let the default action occur,
    i.e. to terminate the process
  • signal(SIGINT, termination_handler);, where termination_handler() is a function that is called the first time
    the signal occurs.

In bash, how can I set up the handler of a signal to be SIG_IGN?

trap "" INT

sets an empty command "" as the signal handler. But does it really set the handler to SIG_IGN?

When bash executes an external command, it will reset signal traps to default, and keep ignored signals still ignored. So it is important to know how to set up a signal handler to be SIG_IGN in bash, and whether setting a signal handler to the empty command "" is the same as setting it to SIG_IGN.

Similar question for how to set up a signal trap to be SIG_DFL in bash.

Thanks.

Best Answer

From the POSIX documentation of the special built-in utility trap:

If action is -, the shell shall reset each condition to the default value. If action is null (""), the shell shall ignore each specified condition if it arises. Otherwise, the argument action shall be read and executed by the shell when one of the corresponding conditions arises.

This means that your script, after trap "" INT, will ignore the INT signal, and that you may reset the trap to default with trap - INT.

Related Question