Linux 提供多種定時機制,若需微秒級甚至納秒級的高精度週期性觸發,POSIX Timer(posix_timer) 是最佳選擇。它基於 CLOCK_REALTIME 或 CLOCK_MONOTONIC 時鐘源,並透過即時訊號(Real-time Signal)非同步通知,避免了傳統 SIGALRM 精度不足與訊號排隊問題。
struct timespec)。SIGRTMIN 以上訊號,支援排隊不丟失。rdtsc 仍能精確計時。編譯需連結即時庫:gcc -o posix_timer posix_timer.c -lrt
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define RDTSC(low, high) __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))
timer_t timer_id;
void timer_handler(int sig, siginfo_t *si, void *uc) {
static unsigned int last_tsc = 0;
unsigned int low, high;
RDTSC(low, high);
unsigned int diff = low - last_tsc;
last_tsc = low;
// 假設 CPU 2.0GHz,轉換為 Hz 顯示
printf("TSC diff: %u, ~%.0f Hz\n", diff, (diff > 0) ? (2000000000.0 / diff) : 0);
}
int main() {
// 封鎖所有訊號,僅處理 SIGRTMIN
sigset_t mask;
sigfillset(&mask);
sigdelset(&mask, SIGRTMIN);
sigprocmask(SIG_SETMASK, &mask, NULL);
// 設定訊號處理函數(SA_SIGINFO 取得 siginfo_t)
struct sigaction sa = {0};
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = timer_handler;
sigfillset(&sa.sa_mask);
if (sigaction(SIGRTMIN, &sa, NULL) == -1) {
perror("sigaction");
exit(EXIT_FAILURE);
}
// 定時器事件設定:觸發 SIGRTMIN
struct sigevent sev = {0};
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGRTMIN;
sev.sigev_value.sival_ptr = &timer_id;
// 建立定時器
if (timer_create(CLOCK_MONOTONIC, &sev, &timer_id) == -1) {
perror("timer_create");
exit(EXIT_FAILURE);
}
// 設定週期:100ms(0.1 秒)
struct itimerspec its = {0};
its.it_value.tv_sec = 0;
its.it_value.tv_nsec = 100 * 1000 * 1000; // 首次觸發
its.it_interval = its.it_value; // 週期觸發
if (timer_settime(timer_id, 0, &its, NULL) == -1) {
perror("timer_settime");
exit(EXIT_FAILURE);
}
printf("POSIX Timer started (100ms interval). Press Ctrl+C to stop.\n");
// 主迴圈:pause() 等待訊號
while (1) pause();
return 0;
}
程式透過 rdtsc 讀取時間戳計數器,計算相鄰兩次觸發的週期差。輸出顯示頻率穩定在 約 10 Hz(100ms),證明 POSIX Timer 能提供穩定、高精度的週期觸發,適合多媒體串流、控制系統、高頻交易等對時間敏感的應用。
CLOCK_MONOTONIC 避免系統時間調整(NTP、手動改時間)影響定時邏輯。timerfd_create() 搭配 epoll 的事件驅動模型。