Linux用户态定时器用法以及犯错总结

采样的时候要用到定时器,定时的进行采样。这时候,就会用到setitimer函数了。

1. 要使用setitimer函数,要包含头文件:#include <sys/time.h>

2. 该函数的原型是:int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value);

3. 参数:

(1)int which:定时器分以下三种

ITIMER_REAL:decrements in real time, and deliversSIGALRM upon expiration.

以系统真实的时间来计算,它送出SIGALRM信号。

ITIMER_VIRTUAL:decrements only  when  the  process  is  executing,  anddeliversSIGVTALRM upon expiration.

以该进程在用户态下花费的时间来计算,它送出SIGV

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个Linux用户定时器的简单例程: ```c #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <time.h> #include <unistd.h> #define TIMER_SIG SIGRTMIN void timer_handler(int sig, siginfo_t *si, void *uc) { printf("Timer expired.\n"); } int main(int argc, char *argv[]) { timer_t timerid; struct sigevent sev; struct itimerspec its; struct sigaction sa; // 设置定时器信号处理函数 sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = timer_handler; sigemptyset(&sa.sa_mask); if (sigaction(TIMER_SIG, &sa, NULL) == -1) { perror("sigaction"); exit(EXIT_FAILURE); } // 创建定时器 sev.sigev_notify = SIGEV_SIGNAL; sev.sigev_signo = TIMER_SIG; sev.sigev_value.sival_ptr = &timerid; if (timer_create(CLOCK_REALTIME, &sev, &timerid) == -1) { perror("timer_create"); exit(EXIT_FAILURE); } // 设置定时器 its.it_value.tv_sec = 5; // 初始定时器时间为5秒 its.it_value.tv_nsec = 0; its.it_interval.tv_sec = 1; // 定时器到期后每1秒重新启动一次 its.it_interval.tv_nsec = 0; if (timer_settime(timerid, 0, &its, NULL) == -1) { perror("timer_settime"); exit(EXIT_FAILURE); } // 循环等待定时器信号 while (1) { sleep(1); } return 0; } ``` 该程序使用 `timer_create()` 创建一个定时器,并使用 `timer_settime()` 设置定时器的初始值和周期值。在定时器到期时,会触发一个 `SIGRTMIN` 信号,该信号将被注册的信号处理函数 `timer_handler()` 捕获并执行。在该例程中,我们简单地打印了一条消息来表示定时器已经到期。 要编译上述程序,请使用以下命令: ``` gcc -o timer timer.c ``` 运行程序,它将等待5秒钟,然后输出一条消息,之后每隔1秒钟再输出一条消息。你可以使用 `Ctrl+C` 组合键来中断程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值