Nimit
Nimit

Reputation: 1712

C : How to pause sigaction Timer

There is one function called test(), I want to call this function in every 30 seconds, Please find my implemented code snippet.

void init_sigaction(void) {
    struct sigaction act;    
    act.sa_handler = test; //test()
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGPROF, &act, NULL);
}


void init_time(void) {
    struct itimerval val;
    val.it_value.tv_sec = 30; //Timer 30 Seconds
    val.it_value.tv_usec = 0;
    val.it_interval = val.it_value;
    setitimer(ITIMER_PROF, &val, NULL);
}

int main()
{
  /*Set the handler for the signal SIG to HANDLER */
    signal(SIGINT, signal_handler);
    init_sigaction();
    init_time();

    Some_other_function();

}

Now I am using some other function, and I want to pause sigaction timer until other function's execution. how can I implemented interrupt for pause?

Thanks,

Upvotes: 1

Views: 3166

Answers (2)

You could consider blocking some signals with e.g. the sigprocmask(2) system call.

However, I strongly recommend reading several times the signal(7) man page. Don't forget that a signal handler can happen any time (including at the worst possible time, e.g. during calls to fprintf or malloc...), so can only call directly or indirectly async-signal-safe functions; and a big lot of library functions are not in this small restricted set. A usual way is to set a volatile sig_atomic_t flag in the signal handler, and test for it outside.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409156

From the manual page of setitimer:

A timer which is set to zero (it_value is zero or the timer expires and it_interval is zero) stops.

Call setitimer with zero times, and with a valid old_value argument to store the current values of the timer, so you can start it again later.

Edit:

How about something like this:

struct itimerval old_timer;

void pause_timer()
{
    struct itimerval zero_timer = { 0 };
    setitimer(ITIMER_PROF, &zero_time, &old_timer);
}

void resume_timer()
{
    setitimer(ITIMER_PROF, &old_timer, NULL);
}

Note The code above is untested, and coded only by reading the manual page.

Upvotes: 3

Related Questions