unsigned alarm(unsigned seconds);
seconds 秒後傳送 SIGALRM 給目前進程seconds=0:取消先前鬧鐘,傳回剩餘秒數#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void handler(int sig) {
puts("Get SIGALRM");
alarm(1); // 重新設定 1 秒
}
int main(void) {
signal(SIGALRM, handler);
alarm(4); // 首次 4 秒
while (1) pause();
return 0;
}
首次 4 秒後觸發,處理函數再設 1 秒,形成週期性觸發。比 setitimer 簡單但精度僅秒級,無法設定微秒間隔。
| 特性 | alarm | setitimer |
|---|---|---|
| 精度 | 秒 | 微秒 |
| 週期性 | 需自行重設 | 內建 it_interval |
| 計時模式 | 僅真實時間 | 三種模式 |
| 可攜性 | POSIX.1 | POSIX.1 |