zoukankan      html  css  js  c++  java
  • setitimer()函数使用

    setitimer()为Linux的API,并非C语言的Standard Library,setitimer()有两个功能,一是指定一段时间后,才执行某个function,二是每间格一段时间就执行某个function,以下程序demo如何使用setitimer()。

    /*  
    Filename    : timer.cpp 
      
    Description : setitimer() set the interval to run function 
     
    Synopsis    : #include <sys/time.h> 
     
                  int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue); 
     
                  struct itimerval { 
     
                    struct timerval it_interval; 
     
                    struct timerval it_value; 
     
                  };  
      
                  struct timeval { 
     
                    long tv_sec; 
     
                    long tv_usec; 
     
                  }              
    */  
     
    #include <stdio.h>    // for printf()  
     
    #include <unistd.h>   // for pause()  
     
    #include <signal.h>   // for signal()  
     
    #include <string.h>   // for memset()  
     
    #include <sys/time.h> // struct itimeral. setitimer()  
      
        
    void printMsg(int);  
        
    int main() {  
      
      // Get system call result to determine successful or failed  
      int res = 0;  
      
      // Register printMsg to SIGALRM   
      signal(SIGALRM, printMsg);  
      
      struct itimerval tick;  
      
      // Initialize struct    
      memset(&tick, 0, sizeof(tick));  
      
      // Timeout to run function first time    
      tick.it_value.tv_sec = 1;  // sec  
      
      tick.it_value.tv_usec = 0; // micro sec.  
      
      // Interval time to run function   
      tick.it_interval.tv_sec = 1;  
      
      tick.it_interval.tv_usec = 0;  
      
      // Set timer, ITIMER_REAL : real-time to decrease timer,  
      
      //                          send SIGALRM when timeout  
      
      res = setitimer(ITIMER_REAL, &tick, NULL);    
      if (res) {  
      
        printf("Set timer failed!!/n");  
      
      }  
        
      // Always sleep to catch SIGALRM signal  
      
      while(1) {  
      
        pause();  
      
      }  
      
      return 0;    
      }  
        
    void printMsg(int num) {  
      
      printf("%s","Hello World!!/n");  
      
    }  

    当setitimer()所执行的timer时间到了,会呼叫SIGALRM signal,itimerval.it_value设定第一次执行function所延迟的秒数, itimerval.it_interval设定以后每几秒执行function,所以若只想延迟一段时间执行function,只要设定 itimerval.it_value即可,若要设定间格一段时间就执行function,则it_value和it_interval都要设定,否则 funtion的第一次无法执行,就别说以后的间隔执行了。

  • 相关阅读:
    什么,你还不会Mysql主从复制???快来看
    MySQL二进制安装(版本:5.7.26)
    MySQL--备份恢复【Mysqdump+xtrabackup(XBK)】
    Mysql日志分析(错误日志,Binlog日志,慢日志),有惊喜哦
    Mysql多实例启动
    Zabbix服务自定义监控和模板
    Centos7安装Zabbix服务端、Zabbix客户端和Win客户端配置(源码编译安装)
    运维工作经验汇总---------高级运维工程师
    手误【删库】 == 跑路,不存在的 ——删瓦辛格
    python——map()函数
  • 原文地址:https://www.cnblogs.com/xf-linux-arm-java-android/p/3740918.html
Copyright © 2011-2022 走看看