Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset SIGINT to default after pointing it some user-defined handler for some time?

Tags:

c++

signals

I use signal(SIGINT,my_handler) to point SIGINT to my_handler. After some time I want to reset it to whatever default handler it points to in general. How can I do that?

like image 997
SkypeMeSM Avatar asked Sep 05 '10 06:09

SkypeMeSM


People also ask

What is the default action for signals?

Signal dispositions Each signal has a current disposition, which determines how the process behaves when it is delivered the signal. Default action is to terminate the process.

What happens when a process receives a signal that it had previously decided to ignore?

The signal is ignored. The signal is queued, and will be processed as soon as the current handler returns.

Could a program continue executing after receiving sigint?

In general, yes, execution continues after the handler returns.

Does Sigaction call the signal handler?

sigaction() can be called with a NULL second argument to query the current signal handler. It can also be used to check whether a given signal is valid for the current machine by calling it with NULL second and third arguments.


2 Answers

Pass SIG_DFL as the func parameter to signal() to reset default behaviour:

signal(SIGINT, SIG_DFL);
like image 97
Carl Norum Avatar answered Oct 24 '22 19:10

Carl Norum


Today, the usage of sigaction is recommended.

Moreover, it allows you to reset automatically the signal handler to default one before your custom handler is called the first time.

SA_RESETHAND

If set, the disposition of the signal shall be reset to SIG_DFL and the SA_SIGINFO flag shall be cleared on entry to the signal handler.

Note: SIGILL and SIGTRAP cannot be automatically reset when delivered; the system silently enforces this restriction.

Otherwise, the disposition of the signal shall not be modified on entry to the signal handler.

In addition, if this flag is set, sigaction() may behave as if the SA_NODEFER flag were also set.

Defining a one time signal handler

#include <signal.h>
#include <stdio.h>

action.sa_handler = my_handler;
action.sa_flags   = SA_RESETHAND;

if (sigaction(SIGINT, &action, NULL) == -1)
{
  perror("Failed to install signal handler for SIGINT");
}

Refer to this post to see how to reset a signal handler to the default one if it's not a one-time handler using sigaction: https://stackoverflow.com/a/24804019/7044965

like image 21
Damien Flament Avatar answered Oct 24 '22 19:10

Damien Flament