linux定时器.cpp

来自「DEMO展示了LINUX下定时器的使用。在LINUX下测试通过。通过信号机制实现」· C++ 代码 · 共 58 行

CPP
58
字号
 //编译时加 -lrt -lpthread
  #include   <stdio.h>   
  #include   <time.h>   
  #include   <signal.h>  
  #include <sys/types.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
 
  void   handle   (sigval_t   v)   
  {   
      time_t   t;   
      char   p[32];   
      time   (&t);   
      strftime   (p,   sizeof   (p),   "%T",   localtime   (&t));   
      printf   ("%s   thread   %ld,   val   =   %d,   signal   captured.\n",   p,   pthread_self   (),   
                      v.sival_int);   
      return;   
  }   
    
  int   
  create   (int   seconds,   int   id)   
  {   
      timer_t   tid;   
      struct   sigevent   se;   
      struct   itimerspec   ts,   ots;   
      memset   (&se,   0,   sizeof   (se));   
      se.sigev_notify   =   SIGEV_THREAD;   
      se.sigev_notify_function   =   handle;   
      se.sigev_value.sival_int   =   id;   
      if   (timer_create   (CLOCK_REALTIME,   &se,   &tid)   <   0)   
          {   
              perror   ("timer_creat");   
              return   -1;   
          }   
      puts   ("timer_create   successfully.");   
      ts.it_value.tv_sec   =   3;   
      ts.it_value.tv_nsec   =   0;   
      ts.it_interval.tv_sec   =   seconds;   
      ts.it_interval.tv_nsec   =   0;   
      if   (
timer_settime   (tid,   TIMER_ABSTIME,   &ts,   &ots)   <   0)   
          {   
              perror   ("timer_settime");   
              return   -1;   
          }   
      return   0;   
  }   
  
  int main()
  {
  	int nRet = create(3, SIGALRM);
  	while(1)
  	{
  	}
  	return 0;
  }
  

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?