Reputation: 46
I have started getting my hands of signals in Linux but here is some strange behavior happening in my code. I have just started and I searched for it too but I have not found anything, sorry if the question is too lame, here is the code-
void Handler(int sig ){
printf("Inside Handler\n");
}
int main(int argc, char * argv[], char * envp[]){
if( signal(SIGINT, Handler) ==SIG_ERR )
exit(EXIT_FAILURE);
for(size_t i = 0; ; i++){
printf("%d\n", i);
sleep(2);
}
}
I know printf
, signal
calls are not the good idea to use but I have not studied sigaction
till now. Now according to my book and others tutorial if I press ctrl+c
then it has to call Handler
every time but here is the strange thing: when I am pressing ctrl+c
once, it's calling Handler
but the next time it's terminating the program. Why is this strange thing happening?
Upvotes: 0
Views: 69
Reputation: 46
Here is the code which I have written with your help which is working perfectly fine and I believe this will work nicely in each and every platform
#define _GNU_SOURCE
void Handler(int sig ){
printf("Inside Handler\n");
}
int main(int argc, char *argv[], char *envp[] ){
sighandler_t Action =Handler;
if( Action == SIG_DFL ){
Action = Handler;
}
if( signal(SIGINT, Action ) == SIG_ERR )
exit(EXIT_FAILURE );
for(size_t k = 0 ; ; k++ ){
printf("%d\n", k );
sleep(2);
}
}
Upvotes: 0
Reputation: 3767
The manual page for signal
syscall says:
If the signal signum is delivered to the process, then one of the following happens:
If the disposition is set to SIG_IGN, then the signal is ignored.
If the disposition is set to SIG_DFL, then the default action associated with the signal (see signal(7)) occurs.
If the disposition is set to a function, then first either the disposition is reset to SIG_DFL, or the signal is blocked (see Portability below), and then handler is called with argument signum. If invocation of the handler caused the signal to be blocked, then the signal is unblocked upon return from the handler.
Since the default behavior of SIGINT is to terminate once the signal is reset to default behavior, the subsequent behavior is different.
Upvotes: 1
Reputation: 182769
The behavior of signal
when passed a handler other than SIG_DFL
or SIG_IGN
is undefined. Use sigaction
for this purpose.
As the docs say:
The only portable use of signal() is to set a signal's disposition to
SIG_DFL
orSIG_IGN
. The semantics when using signal() to establish a signal handler vary across systems (and POSIX.1 explicitly permits this variation); do not use it for this purpose.
Upvotes: 0