名称
alarm -%uA0设置闹钟传递信号内容简介
#include <unistd.h> unsigned int alarm(unsigned int seconds) |
描述
alarm() arranges for a%uA0SIGALRM%uA0signal to be delivered to the process in%uA0secondsseconds.
If%uA0seconds%uA0is zero, no new%uA0alarm() is scheduled.
In any event any previously set%uA0alarm() is cancelled.
返回值
alarm() 返回剩余的秒数,直到任何先前预定的报警是由于传递或零,如果没有先前预定的报警。
注意
alarm() and%uA0setitimer() share the same timer calls to one will interfere with use of the other.
sleep() may be implemented using%uA0SIGALRM mixing calls to%uA0alarm() and%uA0sleep() is a bad idea.
调度延迟,以往一样,导致执行任意数量的时间被推迟的进程。
%uA0
系统中的每个进程都有一个私有的闹钟。这个闹钟很像一个计时器,可以设置在一定秒数后闹钟。时间一到,时钟就发送一个信号SIGALRM到进程。
函数原型:unsigned int alarm(unsigned int seconds)
头文件:#include<unistd.h>
函数说明: 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 }
%uA0
运行结果:
首先打印%uA0
5秒后打印%uA0
%uA0
再经过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) }
%uA0
计时器的另一个用途是调度一个在将来的某个时刻发生的动作同时做些其他事情。调度一个将要发生的动作很简单,通过调用alarm来设置计时器,然后继续做别的事情。当计时器计时到0时,信号发送,处理函数被调用。
遵循于
SVr4, POSIX.1-2001, 4.3BSD