C中的多个警报?

编程入门 行业动态 更新时间:2024-10-24 01:58:52
本文介绍了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中的多个警报?

本文发布于:2023-11-27 21:14:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   警报

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!