问题描述
我正在使用GCC编译器和C ++,我想要一个计时器,当倒计时为0时触发中断。
任何想法?提前感谢。
编辑
感谢Adam,做它。
现在。多个计时器并行运行怎么样?
实际上,这些计时器是非常基本的。在NCURSES,我有一个事情的列表。当我按下一个键,其中的一件事会改变颜色5秒。如果我按另一个键,列表中的另一件事情将会做同样的事情。这就像强调字符串取决于用户输入。
一种方法是使用系统调用发送 SIGALRM
到定时器运行时的进程:
void sigalrm_handler b $ b {
//当定时器用完时调用。尽量不要在这里做太多;
//建议的做法是设置一个标志(类型为sig_atomic_t),并有
//代码在其他地方检查该标志(例如在程序的主循环中)
}
...
signal(SIGALRM,& sigalrm_handler); //设置信号处理程序
alarm(10); //从现在起设置一个警报10秒钟
小心注意手册页闹钟
:
I'm using the GCC compiler and C++ and I want to make a timer that triggers an interruption when the countdown is 0.
Any Ideas? Thanks in advance.
EDIT
Thanks to Adam, I know how to do it.
Now. What about multiple timers running in parallel?
Actually, these timers are for something very basic. In NCURSES, I have a list of things. When I press a key, one of the things will change colors for 5 seconds. If I press another key, another thing in the list will do the same. It's like emphasize strings depending on the user input. Is there a simpler way to do that?
One way to do it is to use the alarm(2)
system call to send a SIGALRM
to your process when the timer runs out:
void sigalrm_handler(int sig)
{
// This gets called when the timer runs out. Try not to do too much here;
// the recommended practice is to set a flag (of type sig_atomic_t), and have
// code elsewhere check that flag (e.g. in the main loop of your program)
}
...
signal(SIGALRM, &sigalrm_handler); // set a signal handler
alarm(10); // set an alarm for 10 seconds from now
Take careful note of the cautions in the man page of alarm
:
这篇关于如何实现一个计时器中断C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!