C语言中打开和关闭定时器代码
时间: 2023-03-31 08:01:10 浏览: 127
打开定时器:
```c
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void timer_handler(int signum)
{
printf("Timer expired.\n");
}
int main()
{
struct sigaction sa;
sa.sa_handler = &timer_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGALRM, &sa, NULL) == -1) {
perror("sigaction");
return 1;
}
alarm(5);
while (1) {
printf("Waiting for the timer to expire...\n");
sleep(1);
}
return ;
}
```
关闭定时器:
```c
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void timer_handler(int signum)
{
printf("Timer expired.\n");
}
int main()
{
struct sigaction sa;
sa.sa_handler = &timer_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGALRM, &sa, NULL) == -1) {
perror("sigaction");
return 1;
}
alarm(5);
while (1) {
printf("Waiting for the timer to expire...\n");
sleep(1);
if (/* some condition */) {
alarm(); // 关闭定时器
break;
}
}
return ;
}
```