Search code examples
csignals

How to pause until signal and not have C print?


I'm guessing I need to call some function in my signal handler and I have no idea what it is

My program wants to sleep until it receives some kind of signal. So naturally I used pause(). Now it ran just fine when I sent my app SIGUSR1 however I get a print out of User defined signal 1 which is not what I want because I plan to send many signals and it will make the console unreadable. I tried handling the signal by writing signal(SIGUSR1, mySignalHandler); but now pause() no longer resumes after I receive the signal. Is there some kind of function I need to call from mySignalHandler?


Solution

  • The default behavior when a program receive a USR1 signal is to terminate (see https://www.man7.org/linux/man-pages/man7/signal.7.html, standard signal).

    An empty signal handle will just do what you want: no message will be displayed.

    #include <unistd.h>
    #include <stdio.h>
    #include <signal.h>
    
    static int s_got = 0;
    
    void handler(int s) 
    {
        ++s_got;
    }
    
    int main(void)
    {
        signal(SIGUSR1, handler);
        while(1) {
            pause();
            printf("resumed %d\n", s_got);
        }
        return 0;
    }
    
    :~/so/pause$ gcc -Wall main.c
    :~/so/pause$ ./a.out &
    [1] 2286
    :~/so/pause$ pkill -USR1 a.out
    resumed 1
    :~/so/pause$ pkill -USR1 a.out
    resumed 2
    :~/so/pause$ pkill -USR1 a.out
    resumed 3
    :~/so/pause$ pkill -USR1 a.out
    resumed 4
    :~/so/pause$ pkill -USR1 a.out
    resumed 5
    :~/so/pause$