首页 > 编程知识 正文

linux settimer定时器怎么用,linux开启高精度定时器

时间:2023-05-04 16:39:15 阅读:219385 作者:2712

文章目录 setitimer延时、定时参数返回值工作机制例子 SIGALRM信号获取系统当前时间参数返回值例子

setitimer延时、定时

#include <sys/time.h>
int setitimer(
  int which,
  const struct itimerval * new_value,
  struct itimerval * old_value
);

struct itimerval{
  struct timeval it_interval; //周期执行时间
  struct timeval it_value; //延迟执行时间
};

struct timeval{
  time_t tv_sec; //秒
  suseconds_t tv_usec; //微秒
};

参数

which :
  ITIMER_REAL:以系统真实的时间来计算,送出SIGALRM信号。  ITMER_VIRTUAL:以该进程在用户态下花费的时间来计算,送出SIGVTALRM 信号。
  ITMER_PROF:以该进程在用户态下和内核态下所费的时间来计算,送出SIGPROF信号。

old_value:
  一般置为NULL,用来存储上一次setitimer调用时设置的new_value。

返回值

  调用成功返回0,否则返回-1。

工作机制

it_value倒计时,为0时触发信号,it_value重置为it_interval,继续倒计时,周期执行。

周期执行时,it_value不为0,设置it_interval;
延迟执行时,设置it_value,it_interval为0。

例子 #include <stdio.h>#include <signal.h>#include <sys/time.h>void signalHandler(int signo){ switch (signo){ case SIGALRM: printf("Caught the SIGALRM signal!n"); break; } } //延时1微秒便触发一次SIGALRM信号,以后每隔200毫秒触发一次SIGALRM信号。 int main(int argc, char *argv[]){ //安装SIGALRM信号 signal(SIGALRM, signalHandler); struct itimerval new_value, old_value; new_value.it_value.tv_sec = 0; new_value.it_value.tv_usec = 1; new_value.it_interval.tv_sec = 0; new_value.it_interval.tv_usec = 200000; setitimer(ITIMER_REAL, &new_value, &old_value); f or(;;); return 0; } SIGALRM信号

#include <signal.h>

在POSIX兼容平台上,SIGALRM是在定时器终止时发送给进程的信号。
SIG是信号名的通用前缀。
ALRM是alarm的缩写,即定时器。

要使用定时器,首先要安装SIGALRM信号。如果不安装,进程收到信号后,缺省的动作就是终止当前进程。

获取系统当前时间

#include <sys/time.h>
#include <unistd.h>
int gettimeofday(
  struct timeval * tv,
  struct timezone * tz
);

struct timeval{
  long tv_sec; //秒
  long tv_usec; //微秒
};

struct timezone{
  int tz_minuteswest; //和格林威治时间差了多少分钟
  int tz_dsttime; //日光节约时间的状态
};

参数

tv:返回当前时间
tz:当地时区信息

返回值

  调用成功返回0,否则返回-1。

例子 #include<iostream>#include <stdlib.h>#include <stdio.h>#include <sys/time.h>#include <unistd.h>int main(){struct timeval tv;gettimeofday(&tv,NULL);printf("second:%ldn",tv.tv_sec);//秒printf("millisecond:%ldn",tv.tv_sec*1000 + tv.tv_usec/1000);//毫秒printf("microsecond:%ldn",tv.tv_sec*1000000 + tv.tv_usec); //微秒sleep(3);std::cout << "3s later:" << std::endl;gettimeofday(&tv,NULL);printf("second:%ldn",tv.tv_sec);//秒printf("millisecond:%ldn",tv.tv_sec*1000 + tv.tv_usec/1000);//毫秒printf("microsecond:%ldn",tv.tv_sec*1000000 + tv.tv_usec); //微秒return0;}//获取当前时间,单位毫秒int getCurrentTime(){ struct timeval tv; gettimeofday(&tv,NULL); return tv.tv_sec*1000 + tv.tv_usec/1000;}

参考资料:
https://blog.csdn.net/lixianlin/article/details/25604779
https://blog.csdn.net/zaishaoyi/article/details/20239997
https://baike.baidu.com/item/SIGALRM/22777025
https://blog.csdn.net/xiewenhao12/article/details/78707101
http://c.biancheng.net/cpp/html/142.html

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。