3

I programmed a daemon which usually pauses and do something after getting a signal (I use SIGHUP for waking up it to another process).

Here is my code.

...
static volatile sig_atomic_t saw_hup = 0;

static void sighup_handler(int s)
{
    saw_hup = 1;
}

int main(void)
{
    struct sigaction act_new;

    ...
    sigemptyset(&act_new.sa_mask);
    act_new.sa_handler = sighup_handler;
    sigaction(SIGHUP, &act_new, NULL);

    while(1) {
        saw_hup = 0;

        pause();
        if(saw_hup) {
            do_section_A();
        }
    }
}

As far as I've tested it, it seems that there is some stack for signal, so the signal, which occurs in executing section A, makes the daemon waken up from pause() execute section A again right after finishing section A by previous one.

But, I want the next SIGHUP signal to be blocked and not to execute section A again by it. What I want is to execute section A whenever SIGHUP occurs except for in the middle of section A executed by previous SIGHUP signal. How do I do that?


I think i the problem that section A is executed again right after section A execution by SIGHUP occurred in the middle of section A execution.

Here is my modified code

...
static volatile sig_atomic_t saw_hup = 0;

static void sighup_handler(int s)
{
    saw_hup = 1;
}

int main(void)
{
    struct sigaction act_new;

    ...
    sigemptyset(&act_new.sa_mask);
    act_new.sa_handler = sighup_handler;
    sigaction(SIGHUP, &act_new, NULL);

    while(1) {
        saw_hup = 0;

        pause();
        if(saw_hup) {
            do_section_A();
        }
    }
}

It seems to work as i wanted. does anybody think there is any problem to this code?

SB.Son
  • 31
  • 6
  • 1
    why not move section A to the signal handler? – user3528438 Mar 30 '16 at 13:54
  • i tried to move section A to the signal handler. but, if new SIGHUP signal occurs in the middle of handler execution, it executes signal handler again after finishing the handler function for the previous signal. what i want is for the next signal not to wake up pause(). – SB.Son Mar 30 '16 at 14:18
  • 1
    http://stackoverflow.com/questions/5285414/signal-queuing-in-c – user3528438 Mar 30 '16 at 14:19

1 Answers1

1

pthread_sigmask() can be used to mask signal in thread. sigprocmask() can be used to mask signal in single thread application.

gzh
  • 3,507
  • 2
  • 19
  • 23
  • thank you for answering to my question, gzh. i tried to use sigprocmask() right after pause() and in the end of section A. But, after finishing Section A, section A is executed again by the signal occurred in the middle of previous signal's execution. So, what i want is for the next signal not to wake up pause(). – SB.Son Mar 30 '16 at 14:10
  • @SB.Son, you should reconsider your processing flow, not only on how to block signals. please refer to the answer provided by pilcrow. – gzh Mar 31 '16 at 01:26