linux定时器函数和优先级,linux 定时器函数

先看代码:例1,alarm()

#include #include #include #include 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 #include #include #include #include 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值