写一段设置定时器的代码 C语言
时间: 2023-06-02 20:06:48 浏览: 55
Sure, here is an example code to set a timer in C programming language:
```
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void timer_handler(int signum)
{
printf("Timer expired.\n");
}
int main()
{
struct sigaction sa;
struct itimerval timer;
// Set the timer handler
sa.sa_handler = &timer_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
// Install the timer handler
if (sigaction(SIGALRM, &sa, NULL) == -1) {
perror("Failed to install signal handler");
return 1;
}
// Configure the timer
timer.it_value.tv_sec = 5; // first timer 5s
timer.it_value.tv_usec = 0;
timer.it_interval.tv_sec = 1; // recurring timer every 1s
timer.it_interval.tv_usec = 0;
// Start the timer
if (setitimer(ITIMER_REAL, &timer, NULL) == -1) {
perror("Failed to start timer");
return 1;
}
// Wait for the timer to expire
while (1) {
sleep(1);
}
return 0;
}
```
This code sets up a timer that will expire after 5 seconds (and print a message), and then will continue to expire every 1 second after that. The `sigaction` function is used to register a signal handler for `SIGALRM` (the signal that will be sent when the timer expires), and the `setitimer` function is used to start the timer. Finally, the program just waits for the timer to expire by calling `sleep` in a loop.