如何使用setitimer来定时

来源:互联网 发布:创意 书 知乎 编辑:程序博客网 时间:2024/06/06 12:35
对于下面的演示代码,我们完全可以使用sighandler_t signal(int signum, sighandler_t handler);来替代sigaction。
#include <iostream>
#include <signal.h>
#include <string.h>
#include <sys/time.h>

using namespace std;

volatile static long counter = 0;

static void notify( int signum )
{
    assert( signum == SIGALRM );
    ++ counter;
}

static void wait( long timeout_ms )
{
    struct timespec spec;
  
    spec.tv_sec     = timeout_ms / 1000;
    spec.tv_nsec     = (timeout_ms % 1000) * 1000000;
    nanosleep( &spec, NULL );
}

int main( void )
{
    struct itimerval  tim_ticks;
    struct sigaction  act;
    struct sigaction  oldact;

    tim_ticks.it_value.tv_sec          = 0;
    tim_ticks.it_value.tv_usec         = 100;
    tim_ticks.it_interval.tv_sec     = 0;
    tim_ticks.it_interval.tv_usec     = 100;

    sigemptyset( &act.sa_mask );
    act.sa_flags                     = 0;
    act.sa_handler                     = notify;
   
    int res = sigaction( SIGALRM, &act, &oldact );
    if ( res )
    {
        perror( "Fail to install handle: " );
       
        return -1;
    }
   
    res = setitimer( ITIMER_REAL, &tim_ticks, 0 );
   
    if ( res )
    {
        perror( "Fail to set timer: " );
       
        sigaction( SIGALRM, &oldact, 0 );
       
        return -2;
    }
   
    for ( ; ; )
    {
        cout << "counter = " << counter << endl;
        wait( 10 );
    }
   
    return 0;
}

 
原创粉丝点击