C中的多个警报? [英] Multiple alarms in C?
问题描述
这可能是一个非常基本的问题,但我正在使用下面的代码来运行一个简单的警报.它按我的意愿工作,但我想知道是否有可能同时运行多个警报,每个警报在完成时触发不同的功能.有没有办法做到这一点?
This is probably a very basic question, but I'm using the code below to run a simple alarm. It works as I want it to, but I'm wondering if it's at all possible to run multiple alarms simultaneously that each trigger a different function when complete. Is there a way to do that?
#include <signal.h>
#include <sys/time.h>
#include <stdio.h>
#include <time.h>
void alarm_handler(int signum){
printf("five seconds passed!!\n");
}
int main(){
signal(SIGALRM, alarm_handler);
alarm(5);
pause();
return 0;
}
推荐答案
不使用 alarm(2)
,但是,您可以使用 POSIX 计时器来实现您的目标.
Not with alarm(2)
, however, you can use POSIX timers to achieve your goal.
您可以设置每个计时器在到期时运行不同的信号,或者您可以使用单个信号并通过 siginfo_t
将指针传递给计时器,然后您可以根据它来决定在处理程序中做什么.
Either you can set each timer to run a different signal when it expires or you can use a single signal and pass a pointer to the timer with it via siginfo_t
, based on which you can then decide what to do in the handler.
示例:
#include <signal.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
static timer_t tmid0, tmid1;
static void hndlr(int Sig, siginfo_t *Info, void *Ptr)
{
if(Info->si_value.sival_ptr == &tmid0)
write(2, "tmid0\n", 6);
else{
write(2, "tmid1\n", 6);
_exit(0);
}
}
int main()
{
int r = EXIT_SUCCESS;
sigaction(SIGALRM, &(struct sigaction){ .sa_sigaction = hndlr, .sa_flags=SA_SIGINFO }, 0);
printf("%p %p\n", (void*)&tmid0, (void*)&tmid1);
struct sigevent sev = { .sigev_notify = SIGEV_SIGNAL, .sigev_signo = SIGALRM };
sev.sigev_value.sival_ptr = &tmid0;
if(0>timer_create(CLOCK_REALTIME,&sev,&tmid0))
{ r=EXIT_FAILURE; goto out; }
sev.sigev_value.sival_ptr = &tmid1;
if(0>timer_create(CLOCK_REALTIME,&sev,&tmid1))
{ r=EXIT_FAILURE; goto out; }
if(0>timer_settime(tmid0, 0, &(struct itimerspec const){ .it_value={1,0} } , NULL) )
{ r=EXIT_FAILURE; goto out; }
//tmid0 expires after 1 second
if(0>timer_settime(tmid1, 0, &(struct itimerspec const){ .it_value={3,0} } , NULL) )
{ r=EXIT_FAILURE; goto out; }
//tmid1 expires after 3 seconds
for(;;)
pause();
out:
if(r)
perror(0);
return r;
}
这篇关于C中的多个警报?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!