#include <unistd.h>
#include <signal.h>
#include <stdio.h>
void sig_alrm(int signo)
{
printf("this is the alarm function\n");
}
unsigned int mysleep(unsigned int nsecs, __sighandler_t handler)
{
struct sigaction newact, oldact;
unsigned int unslept;
newact.sa_handler = handler;
sigemptyset(&newact.sa_mask);
newact.sa_flags = 0;
sigaction(SIGALRM, &newact, &oldact);
alarm(nsecs);
pause();
unslept = alarm(0);
sigaction(SIGALRM, &oldact, NULL);
return unslept;
}
int main(void)
{
while(1) {
unsigned int n = mysleep(2,sig_alrm);
printf("%d seconds passed !\n",n);
}
return 0;
}
信号模拟 sleep 函数,定时器
最新推荐文章于 2022-06-28 18:10:42 发布
本文介绍了一个用C语言实现的自定义延时函数mysleep。该函数通过设置信号SIGALRM并利用pause函数来达到延时的效果。每经过指定秒数,会调用一个自定义的报警函数sig_alrm,打印消息并返回未睡眠的时间。

879

被折叠的 条评论
为什么被折叠?



