linux定时器  原文出自http://www.cnblogs.com/processakai/archive/2012/04/11/2442294.html

今天看书看到了关于alarm的一些用法,自己有在网上找了些资料看了下;
1。alarm()执行后,进程将继续执行,在后期(alarm以后)的执行过程中将会在seconds秒后收到信号SIGALRM并执行其处理函数。

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
void sigalrm_fn(int sig)
{
    printf("alarm!\n");
    alarm(2);
    return;
}
int main(void)
{
    signal(SIGALRM, sigalrm_fn);
    alarm(1);
    while(1) pause();
}

2.alarm定时器,但是只能精确到秒,然而我们如果需要用到更精准的怎么办?
经过群里的大牛知道,看了下可以用setitimer
 int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue));
 setitimer()比alarm功能强大,支持3种类型的定时器:
    ITIMER_REAL :     以系统真实的时间来计算,它送出SIGALRM信号。
    ITIMER_VIRTUAL : -以该进程在用户态下花费的时间来计算,它送出SIGVTALRM信号。
    ITIMER_PROF :     以该进程在用户态下和内核态下所费的时间来计算,它送出SIGPROF信号。
    setitimer()第一个参数which指定定时器类型(上面三种之一);第二个参数是结构itimerval的一个实例;第三个参数可不做处理。
    setitimer()调用成功返回0,否则返回-1。

下面是关于setitimer调用的一个简单示范,在该例子中,每隔一秒发出一个SIGALRM,每隔0.5秒发出一个SIGVTALRM信号:[code=C/C++]
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
int sec;
void sigroutine(int signo){
    switch (signo){
        case SIGALRM:
            printf("Catch a signal -- SIGALRM \n");
            signal(SIGALRM, sigroutine);
            break;
        case SIGVTALRM:
            printf("Catch a signal -- SIGVTALRM \n");
            signal(SIGVTALRM, sigroutine);
            break;
    }
    return;
}
int main()
{
    struct itimerval value, ovalue, value2;          //(1)
    sec = 5;
    printf("process id is %d\n", getpid());
    signal(SIGALRM, sigroutine);
    signal(SIGVTALRM, sigroutine);
    value.it_value.tv_sec = 1;
    value.it_value.tv_usec = 0;
    value.it_interval.tv_sec = 1;
    value.it_interval.tv_usec = 0;
    setitimer(ITIMER_REAL, &value, &ovalue);     //(2)
    value2.it_value.tv_sec = 0;
    value2.it_value.tv_usec = 500000;
    value2.it_interval.tv_sec = 0;
    value2.it_interval.tv_usec = 500000;
    setitimer(ITIMER_VIRTUAL, &value2, &ovalue);
    for(;;)
        ;
}
setitimer不会引起线程的阻塞、也不会引起线程的切换动作,就是简单的启动一个定时器,开始定时,而且这种定时应该是基于内核的,(windwos的settimer是基于一种消息的模型);setitimer虽然有三种类型ITIMER_REAL,ITIMER_VIRTUAL ITIMER_PROF,但是在同一时间同一进程,一种类型的只能有1个setitimer;
如果我们需要多个定时器怎么办?
3.

[code=C/C++]
#include<stdio.h>  
#include<stdlib.h>  
#include<time.h>  
#include<sys/time.h>  
#include<errno.h>  
#include<string.h>  
#include<unistd.h>  
#include<sys/types.h>  
#include<sys/select.h>  
 
 
int main(int argc, char **argv) 

    unsigned int nTimeTestSec = 0; 
    unsigned int nTimeTest = 0; 
    struct timeval tvBegin; 
    struct timeval tvNow; 
    int ret = 0; 
    unsigned int nDelay = 0; 
    struct timeval tv; 
    int fd = 1; 
    int i = 0; 
    struct timespec req; 
 
    unsigned int delay[20] =  
        {500000, 100000, 50000, 10000, 1000, 900, 500, 100, 10, 1, 0}; 
    int nReduce = 0; //误差  
 
    fprintf(stderr, "%19s%12s%12s%12s\n", "fuction", "time(usec)", "realtime", "reduce"); 
    fprintf(stderr, "----------------------------------------------------\n"); 
    for (i = 0; i < 20; i++) 
    { 
        if (delay[i] <= 0) 
            break; 
        nDelay = delay[i]; 
        //test sleep  
        gettimeofday(&tvBegin, NULL); 
        ret = usleep(nDelay); 
        if(ret == -1) 
        { 
            fprintf(stderr, "usleep error, errno=%d [%s]\n", errno, strerror(errno)); 
        } 
        gettimeofday(&tvNow, NULL); 
        nTimeTest = (tvNow.tv_sec - tvBegin.tv_sec) * 1000000 + tvNow.tv_usec - tvBegin.tv_usec; 
        nReduce = nTimeTest - nDelay; 
 
         fprintf (stderr, "\t usleep       %8u   %8u   %8d\n", nDelay, nTimeTest,nReduce); 
 
         //test nanosleep  
         req.tv_sec = nDelay/1000000; 
         req.tv_nsec = (nDelay%1000000) * 1000; 
 
         gettimeofday(&tvBegin, NULL); 
         ret = nanosleep(&req, NULL); 
         if (-1 == ret) 
         { 
            fprintf (stderr, "\t nanousleep   %8u   not support\n", nDelay); 
         } 
         gettimeofday(&tvNow, NULL); 
         nTimeTest = (tvNow.tv_sec - tvBegin.tv_sec) * 1000000 + tvNow.tv_usec - tvBegin.tv_usec; 
         nReduce = nTimeTest - nDelay; 
         fprintf (stderr, "\t nanosleep    %8u   %8u   %8d\n", nDelay, nTimeTest,nReduce); 
 
         //test select  
         tv.tv_sec = 0; 
         tv.tv_usec = nDelay; 
 
         gettimeofday(&tvBegin, NULL); 
         ret = select(0, NULL, NULL, NULL, &tv); 
         if (-1 == ret) 
         { 
            fprintf(stderr, "select error. errno = %d [%s]\n", errno, strerror(errno)); 
         } 
 
         gettimeofday(&tvNow, NULL); 
         nTimeTest = (tvNow.tv_sec - tvBegin.tv_sec) * 1000000 + tvNow.tv_usec - tvBegin.tv_usec; 
         nReduce = nTimeTest - nDelay; 
         fprintf (stderr, "\t select       %8u   %8u   %8d\n", nDelay, nTimeTest,nReduce); 
 
         //pselcet  
         req.tv_sec = nDelay/1000000; 
         req.tv_nsec = (nDelay%1000000) * 1000; 
 
         gettimeofday(&tvBegin, NULL); 
         ret = pselect(0, NULL, NULL, NULL, &req, NULL); 
         if (-1 == ret) 
         { 
            fprintf(stderr, "select error. errno = %d [%s]\n", errno, strerror(errno)); 
         } 
 
         gettimeofday(&tvNow, NULL); 
         nTimeTest = (tvNow.tv_sec - tvBegin.tv_sec) * 1000000 + tvNow.tv_usec - tvBegin.tv_usec; 
         nReduce = nTimeTest - nDelay; 
         fprintf (stderr, "\t pselect      %8u   %8u   %8d\n", nDelay, nTimeTest,nReduce); 
 
         fprintf (stderr, "--------------------------------\n"); 
 
    } 
     
    return 0; 
}

[/code]

int msSleep(long ms) {

struct timeval tv;

tv.tv_sec = 0;

tv.tv_usec = ms;

return select(0, NULL, NULL, NULL, &tv);

}

上面这段代码作者有这样的话
“老大建议我们在对精度要求较高的情况下使用select()作为定时器,最大的好处就是不会影响信号处理线程安全,而且精度能得到保证。在这个实验中,当时间延时时间较长时,select和pselect表现较差,当时间小于1毫秒时,他们的精确度便提高了,表现与usleep、nanosleep不相上下,有时精度甚至超过后者。

查了下上面4个函数,select,和sleep是可重入函数,在使用的时候会引起线程的切换;所以有“不会影响信号处理线程安全”而usleep,nanosleep,不可重入函数,程序是在暂停状态,也就是不能线程切换;但是不知道setitimer会不会记时;

linux定时器用法的更多相关文章

  1. linux定时器crontab

    linux定时器crontab用法: 1.基本格式 : * * * * * command 分 时 日 月 周 命令 第1列表示分钟1-59 每分钟用*或者 */1表示 第2列表示小时1-23(0表示 ...

  2. linux curl用法详解

    linux ‍‍curl用法详解 ‍‍curl的应用方式,一是可以直接通过命令行工具,另一种是利用libcurl库做上层的开发.本篇主要总结一下命令行工具的http相关的应用, 尤其是http下载方面 ...

  3. [转载]expect spawn、linux expect 用法小记

    原文地址:expect spawn.linux expect 用法小记作者:悟世 使用expect实现自动登录的脚本,网上有很多,可是都没有一个明白的说明,初学者一般都是照抄.收藏.可是为什么要这么写 ...

  4. Linux 定时器应用【转】

    Linux 定时器应用 实验目的 阅读 Linux 相关源代码,学习 Linux 系统中的时钟和定时器原理,即,ITIMER_REAL实时计数,ITIMER_VIRTUAL 统计进程在用户模式执行的时 ...

  5. [转帖]linux lsof 用法简介

    linux lsof 用法简介 https://www.cnblogs.com/saneri/p/5333333.html 1.简介: lsof(list open files)是一个列出当前系统打开 ...

  6. 4412 Linux定时器

    一.Linux定时器基础知识 1.1 定时器的使用范围 延后执行某个操作,定时查询某个状态:前提是对时间要求不高的地方 1.2 内核时间概念 Hz:(系统时钟通过CONFIG_HZ来设置,范围是100 ...

  7. Linux用户态定时器用法以及犯错总结【转】

    转自:http://blog.csdn.net/csdn_logo/article/details/48525703 版权声明:本文为博主原创文章,欢迎转载,转载请注明出处,多谢合作. 采样的时候要用 ...

  8. Smart210学习记录-----linux定时器

    1.内核定时器: Linux 内核所提供的用于操作定时器的数据结构和函数如下: (1) timer_list 在 Linux 内核中,timer_list 结构体的一个实例对应一个定时器 1 stru ...

  9. Javascript的setTimeOut()和setInterval()的定时器用法

    Javascript用来处理延时和定时任务的setTimeOut和setInterval函数应用非常广泛,它们都用来处理延时和定时任务,比如打开网页一段时间后弹出一个登录框,页面每隔一段时间发送异步请 ...

随机推荐

  1. javascript高级编程笔记01(基本概念)

    1.在html中使用JavaScript 1.  <script> 元素 <script>定义了下列6个属性: async:可选,异步下载外部脚本文件. charset:可选, ...

  2. ios App优化

    一. 静态分析(Analyze) 在Xcode菜单栏中点击 ”Product“ -> "Analyze",编译完成后项目工程中可能造成内存泄露的代码就会被标记出来,这样我们就 ...

  3. 几种 Docker 监控工具对比

    轻量级虚拟化容器 Docker,自发布以来便广受业界关注,在开源界和企业界掀起了一阵风.Docker 容器相对于 VM 有以下几个优势:启动速度快:资源利用率高:性能开销小. 从图中可以看出 Dock ...

  4. loadrunner_analysis技巧_average 和 90% percent

    “90% Percent Time” 表示90%的事务response time 都维持在某个值附近,不是 average response time * 90%;  “Average Time” 平 ...

  5. 165. Compare Version Numbers

    题目: Compare two version numbers version1 and version2.If version1 > version2 return 1, if version ...

  6. mybatis UpdateByExampleMapper UpdateByExampleSelectiveMapper

    /** * 通用Mapper接口,Example查询 * * @param <T> 不能为空 * @author liuzh */ public interface UpdateByExa ...

  7. WPF——传实体类

    User u; private void Button_Click_1(object sender, RoutedEventArgs e) //点击登陆按钮,弹出新窗体 { //先判断一下是不是正确的 ...

  8. [HDU 1963] Investment

    Investment Time Limit:10000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu   Descrip ...

  9. mac 软件安装

    [Mac]PS CC 软件下载及破解的详细方法 为github帐号添加SSH keys 在mac下,打开文件都是“Smart Adobe CC Blocker v1.0”已损坏,打不开 brew ma ...

  10. modsecookie

    Cookie parsing added添加cookie解析 现在你可以使用新的可选的过滤器变量(COOKIE_name, COOKIE_NAMES, COOKIE_VALUES)分析cookies. ...