#include
#include
#include
#include
void func()
{
printf("this is func\n");
}
int main()
{
signal(SIGALRM, func); //2s后要执行的函数
alarm();//设置定时2s
while ();
return ;
}
(2)setitimer()函数
在linux下如果对定时要求不太精确的话,使用alarm()和signal()就行了,但是如果想要实现精度较高的定时功能的话,就要使用setitimer函数。
setitimer()为Linux的API,并非C语言的Standard Library,setitimer()有两个功能,一是指定一段时间后,才执行某个function,二是每间格一段时间就执行某个function;
Linux为每个任务安排了3个内部定时器:
ITIMER_REAL:实时定时器,不管进程在何种模式下运行(甚至在进程被挂起时),它总在计数。定时到达,向进程发送SIGALRM信号。
ITIMER_VIRTUAL:这个不是实时定时器,当进程在用户模式(即程序执行时)计算进程执行的时间。定时到达后向该进程发送SIGVTALRM信号。
ITIMER_PROF:进程在用户模式(即程序执行时)和核心模式(即进程调度用时)均计数。定时到达产生SIGPROF信号。ITIMER_PROF记录的时间比ITIMER_VIRTUAL多了进程调度所花的时间。
定时器在初始化是,被赋予一个初始值,随时间递减,递减至0后发出信号,同时恢复初始值。在任务中,我们可以一种或者全部三种定时器,但同一时刻同一类型的定时器只能使用一个。
setitimer函数原型如下:
#include
int setitimer(int which, const struct itimerval *new_value,
struct itimerval *old_value);
Timer values are defined by the following structures:
struct itimerval {
struct timeval it_interval; /* next value */
struct timeval it_value; /* current value */
};
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
it_interval用来指定每隔多长时间执行任务, it_value用来保存当前时间离执行任务还有多长时间。比如说, 你指定it_interval为2秒(微秒为0),开始的时候我们把it_value的时间也设定为2秒(微秒为0),当过了一秒, it_value就减少一个为1, 再过1秒,则it_value又减少1,变为0,这个时候发出信号(告诉用户时间到了,可以执行任务了),并且系统自动把it_value的时间重置为 it_interval的值,即2秒,再重新计数
下面是setitimer简单实例:
#include
#include
#include
#include
#include
void test_func()
{
static count = ;
printf("count is %d\n", count++);
}
void init_sigaction()
{
struct sigaction act;
act.sa_handler = test_func; //设置处理信号的函数
act.sa_flags = ;
sigemptyset(&act.sa_mask);
sigaction(SIGPROF, &act, NULL);//时间到发送SIGROF信号
}
void init_time()
{
struct itimerval val;
val.it_value.tv_sec = ; //1秒后启用定时器
val.it_value.tv_usec = ;
val.it_interval = val.it_value; //定时器间隔为1s
setitimer(ITIMER_PROF, &val, NULL);
}
int main(int argc, char **argv)
{
init_sigaction();
init_time();
while();
return ;
}
可以看出每个一秒输出一个count的值:
下面是运行结果:
[root@localhost 5th]# ./test
count is 0
count is 1
count is 2
count is 3
count is 4
count is 5
count is 6
count is 7
count is 8
count is 9