struct itimerspec 的 tv_nsec)SIGEV_SIGNAL)CLOCK_REALTIME、CLOCK_MONOTONIC 等時鐘源struct sigevent {
int sigev_notify; // SIGEV_SIGNAL/SIGEV_THREAD/SIGEV_NONE
int sigev_signo; // 通知信號編號
union sigval sigev_value; // 傳遞給處理函數的值
};
struct itimerspec {
struct timespec it_interval; // 週期間隔
struct timespec it_value; // 首次觸發/下次觸發
};
struct timespec {
time_t tv_sec; // 秒
long tv_nsec; // 奈秒 (0-999,999,999)
};
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#define rdtsc(low,high) __asm__ __volatile__("rdtsc" : "=a"(low), "=d"(high))
timer_t timerid;
void handler(int sig, siginfo_t *si, void *uc) {
static unsigned last = 0;
unsigned low, high;
rdtsc(low, high);
unsigned diff = low - last;
printf("TSC: %u, diff: %u, freq: %.1f MHz\n", low, diff, diff * 10.0 / 1e6);
last = low;
}
int main(void) {
struct sigaction sa = {0};
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handler;
sigfillset(&sa.sa_mask);
sigdelset(&sa.sa_mask, SIGRTMIN);
sigaction(SIGRTMIN, &sa, NULL);
struct sigevent sev = {0};
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGRTMIN;
sev.sigev_value.sival_ptr = &timerid;
struct itimerspec its = {0};
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 100 * 1000 * 1000; // 100ms
its.it_value = its.it_interval;
timer_create(CLOCK_REALTIME, &sev, &timerid);
timer_settime(timerid, 0, &its, NULL);
for (int i = 0; i < 10; i++) pause();
timer_delete(timerid);
return 0;
}
gcc -o posix_timer posix_timer.c -lrt
./posix_timer
輸出顯示 TSC (Time Stamp Counter) 差值與估算頻率,驗證定時器精度。需連結 -lrt (Real-Time Library)。
timer_create + CLOCK_MONOTONICsetitimer / alarmSIGEV_THREAD 模式