| Sample Code:
# Include <iostream>
Using namespace STD;
# Include <pthread. h>
# Include <unistd. h>
# Include <stdlib. h>
# Include <signal. h>
# Include <pthread. h>
# Include <unistd. h>
# Include <sys/STAT. h>
# Include <string. h>
# Include <time. h>
# Define sigmytimer (sigrtmax)
Int settimer (INT nelaspe, int nmode = 1 );
Void timerroutine (INT signo, siginfo_t * info, void * context );
Int main ()
{
Cout <"proc ID:" <(long) getpid () <"main thread ID:" <pthread_self () <Endl;
Struct sigaction sysact;
// Setup signal handler
Sigemptyset (& sysact. sa_mask );
Sysact. sa_flags = sa_siginfo;
Sysact. sa_sigaction = timerroutine;
Sigaction (sigmytimer, & sysact, null );
Settimer (500 );
Settimer (500 );
Settimer (500 );
While (1)
{
Sleep (1 );
}
Cout <"Quit !!!! "<Endl;
Return 0;
}
Timer_t idlist [20]; // use to save timer ID;
// Mode: 0: oneshot timer; 1: periodicity Timer
Int settimer (INT nelaspe, int nmode)
{
Struct sigevent EVP;
Static int ntimerindex = 0;
EVP. sigev_notify = sigev_signal;
EVP. sigev_signo = sigmytimer;
EVP. sigev_value.sival_ptr = & idlist [ntimerindex];
Int ncreate = timer_create (clock_realtime, & EVP, & idlist [ntimerindex]);
If (ncreate = 0) // success
{
Struct itimerspec value;
Struct itimerspec ovalue;
Value. it_value. TV _sec = nelaspe/1000;
Value. it_value. TV _nsec = (nelaspe % 1000) * (1000*1000 );
If (nmode = 1)
{
Value. it_interval. TV _sec = value. it_value. TV _sec;
Value. it_interval. TV _nsec = value. it_value. TV _nsec;
}
Else
{
Value. it_interval. TV _sec = 0;
Value. it_interval. TV _nsec = 0;
}
If (timer_settime (idlist [ntimerindex], 0, & Value, & ovalue) = 0) // success
{
Cout <"timer ID:" <idlist [ntimerindex] <"nelaspe:" <nelaspe <Endl;
}
}
Else
{
Cout <"create timer error" <Endl;
}
// ++ Ntimerindex;
Return idlist [ntimerindex ++];
}
// Timer singal proc
Void timerroutine (INT signo, siginfo_t * info, void * context)
{
If (signo! = Sigmytimer) return;
// Display time
Time_t currtime;
Time (& currtime );
TM * PTM = localtime (& currtime );
If (PTM)
{
Char sbuf [30];
Sprintf (sbuf, "% 02d: % 02d: % 02d", PTM-> tm_hour, PTM-> tm_min, PTM-> tm_sec );
Cout <sbuf;
}
Cout <"timer_id:" <* (int *) (Info-> si_value.sival_ptr) <"sig_id:" <signo <"thread_id:" <pthread_self () <Endl;
}
Compile:
Librt is a system library. You don't have to worry about its path (in usr/lib). Remember to connect when compiling.
G ++-O demo. cpp-LRT |