写一个c语言程序,要求使用定时器每隔2秒触发打印函数
时间: 2024-12-11 13:45:20 浏览: 45
在C语言中,我们可以使用POSIX定时器功能来实现这个需求,通常通过`timer_create`、`timer_settime`和`timer_delete`等系统调用来管理定时任务。这里是一个简单的示例,它创建了一个定时器,在每两秒调用`print_function`函数:
```c
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/timer.h>
void print_function() {
struct tm *current_time;
time_t raw_time;
time(&raw_time);
current_time = localtime(&raw_time);
printf("Timer triggered at: %04d-%02d-%02d %02d:%02d:%02d\n",
current_time->tm_year + 1900,
current_time->tm_mon + 1,
current_time->tm_mday,
current_time->tm_hour,
current_time->tm_min,
current_time->tm_sec);
}
int main() {
struct itimerspec interval_spec;
timer_t timer_id;
sigevent sev;
int ret;
// 初始化定时器间隔,这里是2秒
interval_spec.it_value.tv_sec = 2;
interval_spec.it_value.tv_nsec = 0; // 精确到秒
// 设置信号事件,当定时器到期时,会执行print_function()
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGRTMIN; // 使用实时信号
sev.sigev_value.sival_ptr = (void *)print_function;
// 创建并初始化定时器
if ((ret = timer_create(CLOCK_REALTIME, &sev, &timer_id)) != 0) {
perror("Failed to create timer");
return ret;
}
// 定义定时器周期
if ((ret = timer_settime(timer_id, 0, &interval_spec, NULL)) != 0) {
perror("Failed to set timer time");
timer_delete(timer_id);
return ret;
}
printf("Timer started. Press Ctrl+C to stop.\n");
// 程序等待用户中断
while (true) {
sleep(1); // 这里假设我们不需要精确到毫秒级别
}
// 清理定时器资源
timer_delete(timer_id);
return 0;
}
```
阅读全文