我希望在给定时间步长的情况下定期运行一个函数。最有效的方法是什么?
我知道我可以花一些时间查看并继续检查,直到 dt 期限过去。但我想知道是否有更好、更高效/更优雅的函数可以使用。
我正在研究虚拟计时器和 sigaction。使用这种方法,我会让 sigaction 处理程序在时间过去时设置一个标志,但我仍然需要坐在 while 循环中检查在我的主函数中设置该标志。或者,我想知道是否真的可以让处理程序运行该函数,但随后我必须传递很多参数,并且据我所知,处理程序不接受参数,因此我必须使用大量全局参数变量。
解决这个问题的最佳方法是什么?
最佳答案
在 *IX'ish 系统上,您可以
- 为
SIGALRM
安装一个处理程序,该处理程序不执行任何操作 - 使用
alarm()
设置闹钟 - 调用阻塞
pause()
如果发送警报信号pause()
将返回并
- 您可以运行相关函数,
- 再次设置闹钟
- 重新调用
pause()
#define _POSIX_SOURCE 1
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
void handler_SIGALRM(int signo)
{
signo = 0; /* Get rid of warning "unused parameter ‘signo’" (in a portable way). */
/* Do nothing. */
}
int main()
{
/* Override SIGALRM's default handler, as the default handler might end the program. */
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = handler_SIGALRM;
if (-1 == sigaction(SIGALRM, &sa, NULL ))
{
perror("sigaction() failed");
exit(EXIT_FAILURE);
}
}
while (1)
{
alarm(2); /* Set alarm to occur in two seconds. */
pause(); /* The call blocks until a signal is received; in theis case typically SIGARLM. */
/* Do what is to be done every 2 seconds. */
}
return EXIT_SUCCESS;
}
关于c - 如何等待时间到期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19500484/