Search code examples
clinuxsignalspause

When do we need to establish signal function again inside a signal handler?


I've got a simple program under linux and it works well:

#include<unistd.h>
#include<stdio.h>
#include<signal.h>
#include<sys/types.h>
void fStop(int signo){
    printf("Hup\n");
}
int main(){
    signal(SIGHUP,fStop);
    for(;;){
        pause();
    }
    return 0;
}

It runs and waits for signals. Each time I send "kill -1 xxx" to it, it prints a "Hup" line. OK

But my questions are:

  1. I found if I remove the "for" loop, seems the pause() won't work after receiving SIGHUP signal. Does it mean that signal will interupt any kind of sleep and suspension functions?

  2. In some linux programs, I see people re-estbalish signal function inside a signal handler like:

void fStop((int signo){
     printf("Hup\n");
     signal(SIGHUP,fStop);//When is this necessary?
}

Just a bit confused how linux signal handler should be designed, when to re-establish handler, depends on different signals? Thanks.


Solution

  • Does it mean that signal will inter[r]upt any kind of sleep and suspension functions?

    Probably not all, but it interrupts pause(), yes.

    From pause()'s documentation (Linux):

    RETURN VALUE

    pause() returns only when a signal was caught and the signal-catching function returned. In this case, pause() returns -1, and errno is set to EINTR.