Chinaunix首页 | 论坛 | 博客
  • 博客访问: 560030
  • 博文数量: 61
  • 博客积分: 2438
  • 博客等级: 大尉
  • 技术积分: 871
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-28 08:04
文章分类
文章存档

2013年(1)

2012年(8)

2011年(15)

2010年(37)

分类: LINUX

2010-10-31 11:45:04

在学习信号时遇到了pause这个函数和alarm函数,可以用这两个处理一个有意思的问题,就是让你的程序每隔一定的时间执行一次function
下面是代码:

/*
 * filename: exec_function.c
 * description: from time to time to perform a function
 **************************************************************************************
 * struct itimerval{
 * struct timerval it_interval;
 * struct timerval it_value;
 * }
 * struct timerval{
 * long tv_sec;
 * long tv_usec;
 * }
 * int setitimer( int which, const struct itimerval *value, struct itimerval *ovalue );
 **************************************************************************************
 */


#include <stdio.h> //printf()

#include <unistd.h> //pause()

#include <signal.h> //signal()

#include <string.h> //memset()

#include <sys/time.h> //struct itimerval, setitimer()


void printMsg(int);

int main(void)
{
    int res = 0;
    struct itimerval tick;

    signal( SIGALRM, printMsg );
    memset( &tick, 0, sizeof(tick) );

    tick.it_value.tv_sec = 1;
    tick.it_value.tv_usec = 0;
    tick.it_interval.tv_sec = 1;
    tick.it_interval.tv_usec = 0;

    res = setitimer( ITIMER_REAL, &tick, NULL );
    if( res ){
        printf( "set timer failed\n" );
    }
    //int i = 5;
    while( 1 ){
        pause();
    }

    return 0;
}

void printMsg(int sig)
{
    printf( "Hello, world !\n" );
}

程序在setitimer设置的时间到了之后就会呼叫SIGALRM signal,函数setitimer的第二个参数设置timeout时间,timerval it_value 设置第一次执行function的延迟秒数,timerval it_interval 设置以后每隔多长时间执行一次function, 函数setitimer第一个参数ITIMER_REAL表示一read-time方式减少timer,在timerout时会发送出SIGARLM signal,第三个参数会存放旧的timeout,如果不需要就NULL。
while(1)是调用pause函数无限等待SIGARLM signal 以间隔执行function。

如有什么不对的地方还希望指出来。。。

阅读(5198) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-10-31 19:21:45

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com