linux下的alarm函数,alarm()函数 Unix/Linux

alarm函数用于在指定秒数后向进程发送SIGALRM信号。它取消任何先前设置的闹钟并返回剩余时间。当SIGALRM信号到达且未处理时,进程会被终止。示例代码展示了如何设置闹钟、获取剩余时间以及处理SIGALRM信号。闹钟功能可用于实现定时任务和进程延迟。
摘要由CSDN通过智能技术生成

名称

alarm -设置闹钟传递信号

内容简介

#include

unsigned int alarm(unsigned intseconds);

描述

alarm() arranges for a SIGALRM signal to be delivered to the process in secondsseconds.

If seconds is zero, no new alarm() is scheduled.

In any event any previously set alarm() is cancelled.

返回值

alarm() 返回剩余的秒数,直到任何先前预定的报警是由于传递或零,如果没有先前预定的报警。

注意

alarm() and setitimer() share the same timer; calls to one will interfere with use of the other.

sleep() may be implemented using SIGALRM; mixing calls to alarm() and sleep() is a bad idea.

调度延迟,以往一样,导致执行任意数量的时间被推迟的进程。

系统中的每个进程都有一个私有的闹钟。这个闹钟很像一个计时器,可以设置在一定秒数后闹钟。时间一到,时钟就发送一个信号SIGALRM到进程。

函数原型:unsigned int alarm(unsigned int seconds);

头文件:#include

函数说明: alarm()用来设置信号SIGALRM在经过参数seconds指定的秒数后,传送给目前的进程。如果参数seconds为0,则之前设置的闹钟会被取消,并将剩下的时间返回。

返回值:如果调用此alarm()前,进程已经设置了闹钟时间,则返回上一个闹钟时间的剩余时间,否则返回0。 出错返回-1。

例1:

int main(int argc, char *argv[]) {

unsigned int timeleft;

printf( "Set the alarm and sleep\n" ); alarm( 10 ); sleep( 5 );

timeleft = alarm( 0 ); //获得上一个闹钟的剩余时间:5秒 printf( "\Time left before cancel, and rearm: %d\n", timeleft );

alarm( timeleft );

printf( "\Hanging around, waiting to die\n" ); pause(); //让进程暂停直到信号出现

return EXIT_SUCCESS;

}

运行结果:

首先打印   Set the alarm and sleep

5秒后打印  Time left before cancel, and rearm: 5

Hanging around, waiting to die

再经过5秒,程序结束

除非进程为SIGALRM设置了处理函数,否则信号将杀死这个进程。比较下例中signal(SIGALRM, wakeup);语句打开与关闭的区别。

例2:

static void timer(int sig) { static int count=0; count++;

printf("\ncount = %d\n", count);

if(sig == SIGALRM) { printf("timer\n"); }

signal(SIGALRM, timer); alarm(1);

if (count == 5) alarm(0); return; }

int main(int argc, char *argv[]) { signal(SIGALRM, timer); alarm(1); while(1);

}

计时器的另一个用途是调度一个在将来的某个时刻发生的动作同时做些其他事情。调度一个将要发生的动作很简单,通过调用alarm来设置计时器,然后继续做别的事情。当计时器计时到0时,信号发送,处理函数被调用。

遵循于

SVr4, POSIX.1-2001, 4.3BSD

另请参阅

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值