Search code examples
clinuxsystems-programming

I am generating signal and facing the strange behaviour


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?


Solution

  • 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);
    }
    
    }