作者:潇洒树春不_970 | 来源:互联网 | 2023-05-17 05:26
对于下面的演示代码,我们完全可以使用sighandler_tsignal(intsignum,sighandler_thandler);来替代sigaction。#include&
对于下面的演示代码,我们完全可以使用sighandler_t signal(int signum, sighandler_t handler);来替代sigaction。
#include
#include
#include
#include
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 = " < wait( 10 );
}
return 0;
}