linux 定时器函数

本文介绍了C语言中用于进程定时的两个函数:alarm()和setitimer()。通过示例代码展示了如何使用它们实现周期性的任务执行,如限制低速IO操作的时间、检查进程状态等。setitimer()相比alarm()更加强大,能够设置不同的计数模式。
摘要由CSDN通过智能技术生成

先看代码:例1,alarm()

#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>

void alarm_handler(int sig)
{   
printf("hello!--sig:%d\n",sig);
alarm(1);
}

int main()
{
if (signal(SIGALRM, alarm_handler) == SIG_ERR) {   //安装信号,SIGALRM的编号为14 
perror("signal");
return 0;
}
alarm(1);    
while(1) {  //让进程一直存在
    pause();
}    
return 0;
}

结果:

[lgh@localhost test]$ ./a.out
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
---------------------------------------------

它会每秒打印一行"hello!--sig:14".

应用:使进程定期性地做某些操作.例如,给低速的IO操作给个时间上限,定期查看进程是否存在,连接是否中断等.

例2:setitimer(),这个比alarm()强大,可以有3种模式进行计数.

#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include <sys/time.h>

void alarm_handler(int sig)
{   
printf("hello!--sig:%d\n",sig);
}

int main()
{
 struct itimerval t;   
 /* 第一次执行前的时间间隔*/
 t.it_value.tv_usec = 0;   
 t.it_value.tv_sec = 3; 
 /* 以后每间再次执行的时间间隔*/
 t.it_interval.tv_usec = 0;    
 t.it_interval.tv_sec = 1;    
     
 if( setitimer(ITIMER_REAL, &t, NULL) < 0 ){
 perror("settimer");        
 return -1;    
 }
 if (signal( SIGALRM, alarm_handler) == SIG_ERR) {
 perror("signal");
 return -1;
}    
 while(1){        
 pause();    
 }
return 0;
}

/*
int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue); 
int which:
  ITIMER_REAL : 以系统真实的时间来计算,时间到发送SIGALRM信号。
  ITIMER_VIRTUAL :以该进程在用户态下花费的时间来计算,时间到发送SIGVTALRM信号。 
  ITIMER_PROF : 以该进程在用户态下和内核态下所费的时间之和来计算,时间到发送SIGPROF信号。

struct itimerval { 
struct timerval it_interval; //执行第一次后,以后每次计数的间隔
struct timerval it_value;  //第一次计数的时间间隔
}; 
 
struct timeval { 
long tv_sec; 
long tv_usec; 
}
*/             


结果:

[lgh@localhost test]$ ./a.out
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
---------------------------------------

启动程序后,隔3秒打印第一行,接下来每1秒打印一行.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xxpr_ybgg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值