1. Timer on Windows
#define WIN32_LEAN_AND_MEAN
#include “windows.h”
UINT tid;
VOID CALLBACK TimerHandler(HWND hWnd, UINT uMsg, UINT idEvent, DWORD dwTime) {
printf(”Timer called @ [%ld]/n”, dwTime);
}
static BOOL WINAPI SignalHandler(DWORD event) {
switch (event) {
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
KillTimer((HWND)NULL, tid);
// Notify not to call other handlers.
return FALSE;
}
return TRUE;
}
int main(int argc, char **argv) {
MSG msg;
if (!SetConsoleCtrlHandler(SignalHandler, TRUE/*add*/)) {
printf(”SetConsoleCtrlHandler error - %d”, GetLastError());
}
if (!(tid = SetTimer((HWND)NULL, 0, 1000, (TIMERPROC)TimerHandler))) {
printf(”SetTimer error - %d”, GetLastError());
}
while (GetMessage(&msg, (HWND)NULL, 0, 0)) {
TranslateMessage(&msg); // translates virtual-key codes
DispatchMessage(&msg); // dispatches message to window
}
// remove our handler from the list of handlers
SetConsoleCtrlHandler(SignalHandler, FALSE);
}
2. Timer on Linux
#include “stdio.h”
#include “unistd.h”
#include “errno.h”
#include “time.h”
#include “sys/time.h”
#include “signal.h”
#define SIGTIMER (SIGRTMAX)
static timer_t tid;
timer_t SetTimer(int signo, int sec, int mode) {
static struct sigevent sigev;
static timer_t tid;
static struct itimerspec itval;
static struct itimerspec oitval;
// Create the POSIX timer to generate signo
sigev.sigev_notify = SIGEV_SIGNAL;
sigev.sigev_signo = signo;
sigev.sigev_value.sival_ptr = &tid;
if (timer_create(CLOCK_REALTIME, &sigev, &tid) == 0) {
itval.it_value.tv_sec = sec / 1000;
itval.it_value.tv_nsec = (long)(sec % 1000) * (1000000L);
if (mode == 1) {
itval.it_interval.tv_sec = itval.it_value.tv_sec;
itval.it_interval.tv_nsec = itval.it_value.tv_nsec;
} else {
itval.it_interval.tv_sec = 0;
itval.it_interval.tv_nsec = 0;
}
if (timer_settime(tid, 0, &itval, &oitval) != 0) {
perror(”time_settime error!”);
}
} else {
perror(”timer_create error!”);
return -1;
}
return tid;
}
void SignalHandler(int signo, siginfo_t* info, void* context) {
if (signo == SIGTIMER) {
struct timeval tv;
time_t t;
struct tm *tm;
gettimeofday(&tv, NULL);
t = tv.tv_sec;
tm = localtime(&t);
printf(”Timer called @ [%02d:%02d:%02d.%03d]/n”, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec / 1000);
} else if (signo == SIGINT) {
timer_delete(tid);
perror(”Crtl+c cached!”);
exit(1); // exit if CRTL/C is issued
}
}
int main(int argc, char **argv) {
struct sigaction sigact;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = SA_SIGINFO;
sigact.sa_sigaction = SignalHandler;
// set up sigaction to catch signal
if (sigaction(SIGTIMER, &sigact, NULL) == -1) {
perror(”sigaction failed”);
return -1;
}
// Establish a handler to catch CTRL+c and use it for exiting.
sigaction(SIGINT, &sigact, NULL);
tid = SetTimer(SIGTIMER, 1000, 1);
// Loop forever. The application will exit in the signal handler
// when a SIGINT is issued (CRTL+c will do this).
for(;;) pause();
return 0;
}