linux alarm函数clock,linux c之alarm函数的使用,定时器的实现

#include

#include

#include

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

unsigned int timeleft;

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

//设置定时器,时钟一到就发送一个信号SIGALRM到进程。

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;

}

#include

#include

#include

#include

#include

#include

#include

#include

int isExit = 1;

//通过调用alarm来设置计时器,然后继续做别的事情。当计时器计时到0时,信号发送,处理函数被调用。

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);//定时1s

if (count == 5)

{

alarm(0);

isExit = 0;

}

return;

}

//linux定时器的实现

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

signal(SIGALRM, timer);//执行定时器函数

printf("wait 1s\n");

alarm(1); //定时1s

while (isExit)

{

};

printf("finish\n");

return 0;

}

你可能感兴趣的:(linux,alarm函数clock)