最常用的就是setitimerr和alarm()两个
这里我们说第一个
struct itimerval
{
struct timeval it_interval; /* next value /
struct timeval it_value; / current value /
};
struct timeval
{
long tv_sec; / seconds /
long tv_usec; / microseconds */
};
介绍一下,首先初始化这两个结构体,lit_value表示系统运行多长时间后执行中断。 it_interval表示多少间隔执行中断。
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <string.h>
void test()
{
printf("time interrupt\r\n");
}
int main(int argc,char *argv[])
{
int i=0;
struct itimerval time_bit;
memset(&time_bit,0,sizeof(time_bit));
//表示系统运行3s后开始执行定时器中断,且中断间隔为2s.
time_bit.it_value.tv_sec=3;
time_bit.it_value.tv_usec=0;
time_bit.it_interval.tv_sec=2;
time_bit.it_interval.tv_usec=0;
signal(SIGALRM,test);
setitimer(ITIMER_REAL,&time_bit,NULL);
while(i++<10)
{
printf("time is %d\r\n",i);
sleep(1);
}
}
运行结果如下
time is 1
time is 2
time is 3
time interrupt
time is 4
time is 5
time interrupt
time is 6
time is 7
time interrupt
time is 8
time is 9
time interrupt
time is 10
root@VM-0-3-ubuntu:/home/ubuntu/fuxi#