zoukankan      html  css  js  c++  java
  • Linux struct itimerval使用方法

    版权声明:本文为博主原创文章。未经博主同意不得转载。 https://blog.csdn.net/hbuxiaofei/article/details/35569229

    先看一段代码

    #include <stdio.h>
    #include <time.h>
    #include <sys/time.h>
    #include <stdlib.h>
    #include <signal.h>
    
    
    static int count = 0;
    
    
    void set_timer()
    {
    	struct itimerval itv;
    
    
    	itv.it_value.tv_sec = 3;    //timer start after 3 seconds later
    	itv.it_value.tv_usec = 0;
    
    
    	itv.it_interval.tv_sec = 1;
    	itv.it_interval.tv_usec = 0;
    
    
    	setitimer(ITIMER_REAL,&itv,NULL);
    }
    
    
    void signal_handler(int m)
    {
    	count ++;
    	printf("%d
    ",count);
    }
    
    
    int main()
    {
    	signal(SIGALRM,signal_handler);
    	set_timer();
    	while(count < 10);
    	exit(0);
    	return 0;
    
    }
    

    这段代码实现的功能:3秒钟后启动定时器。然后每隔1秒钟向终端打印count的递增值,当count到10时程序退出。

    结构体原型:

    struct itimerval {
                    struct timeval it_interval; /* next value */
                    struct timeval it_value;    /* current value */
                };
    
    
    struct timeval {
                    long tv_sec;                /* seconds */
                    long tv_usec;               /* microseconds */
                };
    即:

    struct itimerval {
        struct timeval it_interval; /* 计时器重新启动动的间歇值 */
        struct timeval it_value;    /* 计时器安装后首先启动的初始值 */
    };
    
    struct timeval {
        long tv_sec;                /* 秒 */
        long tv_usec;               /* 微妙(1/1000000) */
    };

    再来看这个函数:

    int setitimer(int which, const struct itimerval *value,struct itimerval *ovalue);

    setitimer()将value指向的结构体设为计时器的当前值,假设ovalue不是NULL,将返回计时器原有值。

    which:间歇计时器类型,有三种选择

    ITIMER_REAL      //数值为0,计时器的值实时递减,发送的信号是SIGALRM。


    ITIMER_VIRTUAL //数值为1,进程运行时递减计时器的值,发送的信号是SIGVTALRM。


    ITIMER_PROF     //数值为2,进程和系统运行时都递减计时器的值。发送的信号是SIGPROF。

    返回说明: 
    成功运行时,返回0。失败返回-1。errno被设为下面的某个值 
    EFAULT:value或ovalue是不有效的指针
    EINVAL:其值不是ITIMER_REAL。ITIMER_VIRTUAL 或 ITIMER_PROF之中的一个





查看全文
  • 相关阅读:
    RSA
    DES
    MD5
    增删改查
    [转]数据绑定之DataFormatString
    分页通用存储过程(未验证)
    浅谈sql中的in与not in,exists与not exists的区别
    [转]order by 1是什么意思?
    bak骗子公司
    Performance Considerations for Entity Framework 4, 5, and 6
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10626440.html
  • Copyright © 2011-2022 走看看