写一个Linux系统下的定时器demo
时间: 2024-05-01 19:16:42 浏览: 154
以下是一个简单的Linux系统下的定时器demo,使用了C语言和POSIX定时器API:
```
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
void timer_handler(int signum)
{
printf("Timer expired.\n");
}
int main()
{
timer_t timerid;
struct sigevent sigev;
struct itimerspec timer_spec;
// 创建定时器信号处理函数
sigev.sigev_notify = SIGEV_SIGNAL;
sigev.sigev_signo = SIGUSR1;
sigev.sigev_value.sival_ptr = &timerid;
if (timer_create(CLOCK_REALTIME, &sigev, &timerid) == -1) {
perror("timer_create");
exit(EXIT_FAILURE);
}
// 设置定时器时间
timer_spec.it_value.tv_sec = 5;
timer_spec.it_value.tv_nsec = 0;
timer_spec.it_interval.tv_sec = 0;
timer_spec.it_interval.tv_nsec = 0;
if (timer_settime(timerid, 0, &timer_spec, NULL) == -1) {
perror("timer_settime");
exit(EXIT_FAILURE);
}
// 设置定时器信号处理函数
struct sigaction sa;
sa.sa_handler = timer_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGUSR1, &sa, NULL) == -1) {
perror("sigaction");
exit(EXIT_FAILURE);
}
// 等待定时器信号
printf("Waiting for timer expiration...\n");
pause();
return 0;
}
```
此程序创建了一个定时器,设置了定时器时间为5秒,并且设置了一个定时器信号处理函数,当定时器时间到时,会触发SIGUSR1信号,从而执行定时器信号处理函数。程序会等待定时器信号的到来,直到定时器时间到达。
阅读全文