Linux下定時器的範例程式碼

來源:互聯網
上載者:User
Linux下定時器的問題
範例程式碼:

#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;
}

編譯:

librt是一個系統庫,你不必管他的路徑(在usr/lib中),在編譯時間記得串連就行了。

g++ -o demo demo.cpp -lrt

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.