Linux 上的 C 异步、定时函数调用?
Linux 上的 C 语言在一定延迟后异步调用函数(如 JavaScript 的 setTimeout
)或设置重复计时器定期调用它(类似于 setInterval
)的最简单、最有效的方法是什么代码>)?
虽然这个问题适用于Linux,但我希望有一种跨平台的方法。
What is the easiest, most effective way in C on Linux to asynchronously call a function after a certain delay (like JavaScript's setTimeout
) or set a repetitive timer call it periodically (similar to setInterval
)?
Though this question applies to Linux, I hope there is a method that is cross-platform.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的 Linux 特定解决方案是使用
alarm
函数:getitimer
和setitimer
函数可用于创建更高精度的计时器。 (更多...)。The simplest Linux specific solution is to use the
alarm
function:getitimer
andsetitimer
functions can be used to create timers with higher-precisions. (more...).有两种方法可以实现:
首先,正如另一个答案中提到的,使用
alarm()
或setitimer()
触发信号。这两个功能在任何遵循 POSIX 的操作系统中都可用;还有第三个函数,名为ualarm()
,它已于 2008 年被废弃。缺点是在信号处理程序中执行任何重要操作(例如 I/O 或其他系统调用)都是不安全的,所以实际上您想要做的可能就是设置一个标志并让其他东西拿起它。第二种是使用一个线程,该线程休眠一定的时间间隔,然后调用您的函数。 POSIX 在 20 世纪 90 年代初将线程标准化为扩展,大多数支持线程的现代操作系统都支持 POSIX 线程。这里的陷阱是,您必须了解让两个执行上下文共享相同数据空间的含义并相应地设计您的程序,否则您将遇到调试起来可能会是一场噩梦的问题。
请注意,闹钟和睡眠仅承诺在至少指定的时间过去后执行它们的操作,因此您无法保证实时获得的准确性操作系统。
There are two ways to go about it:
First, as mentioned in another answer, is signals triggered using
alarm()
orsetitimer()
. Both functions are available in any OS that adheres to POSIX; there's a third function calledualarm()
which was obsoleted in 2008. The down side is that it's unsafe to do anything significant (e.g., I/O or other system calls) in a signal handler, so really all you want to do is maybe set a flag and let something else pick it up.Second is to use a thread that sleeps for a certain interval and then calls your function. POSIX standardized threads as an extension in the early 1990s, and most modern OSes that support threads support POSIX threads. The pitfall here is that you have to understand the implications of having two execution contexts share the same data space and design your program accordingly or you're going to run into problems that can be a nightmare to debug.
Be aware that alarms and sleeps only promise to do what they do after at least the specified amount of time has elapsed, so you're not guaranteed the kind of accuracy you'd get on a real-time operating system.