Linux 上的 C 异步、定时函数调用?

发布于 2024-09-19 19:26:59 字数 175 浏览 5 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

锦上情书 2024-09-26 19:26:59

最简单的 Linux 特定解决方案是使用 alarm 函数:

void alarm_handler (int signum)
{
    printf ("Five seconds passed!\n");
}

signal (SIGALRM, alarm_handler);
alarm (5);

getitimersetitimer 函数可用于创建更高精度的计时器。 (更多...)。

The simplest Linux specific solution is to use the alarm function:

void alarm_handler (int signum)
{
    printf ("Five seconds passed!\n");
}

signal (SIGALRM, alarm_handler);
alarm (5);

getitimer and setitimer functions can be used to create timers with higher-precisions. (more...).

青春如此纠结 2024-09-26 19:26:59

有两种方法可以实现:

首先,正如另一个答案中提到的,使用 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() or setitimer(). Both functions are available in any OS that adheres to POSIX; there's a third function called ualarm() 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文