3

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.

3

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.

1

I took this script:

#!/bin/bash
trap "" INT
trap - INT

And ran:

$ strace bash script.sh 2>&1 | grep INT

Among the output, I see:

read(3, "#!/bin/bash\ntrap \"\" INT\ntrap - I"..., 80) = 35
read(255, "#!/bin/bash\ntrap \"\" INT\ntrap - I"..., 35) = 35
rt_sigaction(SIGINT, {sa_handler=SIG_IGN, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f24e88f2030}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f24e88f2030}, 8) = 0
rt_sigaction(SIGINT, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f24e88f2030}, {sa_handler=SIG_IGN, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f24e88f2030}, 8) = 0

Given the sa_handler=SIG_IGN in the first call to rt_sigaction() and the sa_handler=SIG_DFL in the second, it looks like trap "" INT is causing bash to really ignore the signal, and trap - INT is causing it to reset to the default handler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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