Skip to content
Advertisement

different ways to ignore a signal?

Im’ new to Linux and signal handling. the signal function prototype is

sighandler_t signal(int signum, sighandler_t handler);

below is my questions:

Q1-if I want to ignore SIGINT signal, then I just need to simply code as: signal(SIGINT, SIG_IGN);, is my understanding corrct?

Q2-What if I code as:

void sigint_handler(int sig) 
{
   //do thing
}

int main() 
{
    /* Install the SIGINT handler */         
    if (signal(SIGINT, sigint_handler) == SIG_ERR)  
       unix_error("signal error");                
    
    pause(); /* Wait for the receipt of a signal */  
    
    return 0;
}

since my own sigint_handler does nothing, it is pretty much like ignoring the SIGINT, so can I say this approach is fundamentally the same as signal(SIGINT, SIG_IGN);?

Q3-where does the SIG_IGN locate? Is it in the .code segment in the user’s process address space as: enter image description here

if my assumption is correct, does the compiler automacially inject this handler into the compiled code?

Advertisement

Answer

if I want to ignore SIGINT signal, then I just need to simply code as: signal(SIGINT, SIG_IGN);, is my understanding corrct?

Yes, but the docs for signal recommend using sigaction. signal‘s semantics vary by system, while sigaction‘s are more consistent.

does the compiler automacially inject this handler into the compiled code?

No. The compiler doesn’t create an empty handler for SIG_IGN. It literally tells the OS to ignore the signal for the process. It’s not a function pointer but a value signal treats specially.

since my own sigint_handler does nothing, it is pretty much like ignoring the SIGINT, so can I say this approach is fundamentally the same as signal(SIGINT, SIG_IGN);?

While both effectively ignore the signal, there are differences.

  • When using a signal handler, a blocking syscall might return prematurely with error EINTR to allow the signal handler to run. This won’t happen with SIG_IGN.
  • SIG_IGN will survive exec, but a handler doesn’t.
  • On some systems, the signals’s disposition is reset to SIG_DFL when the signal handler is called, so your code would only ignore the first instance of the signal on such systems.
  • There are other differences, which may vary by platform.
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement