How to limit the execution time of a function in C/POSIX?

血红的双手。 提交于 2019-12-06 05:22:51

Just to note that the general capability you're looking for here is called cost enforcement. For example see this article by Wellings or in Leung, et. al.'s great book. The answers above are focused on achieving it in userspace; some RTOS or languages support it (not linux) as a general mechanism.

One example OS that provides this is the AUTOSAR OS (spec linked). Note that this OS provides execution time enforcement, which is slightly different from deadline enforcement. Execution time enforcement keeps getting harder, as it relies on some ability to measure the actual cost expended (usually with hardware cooperation). With the complexity of today's processors, it's difficult and costly to measure this — not to mention that the meaning of the measurements (due to nonlinear execution and all sorts of other cool stuff) are hard to interpret — and thus difficult event to compute a (worst- or common-) case estimate of a particular section of code's execution time.

Slightly off-topic, but Ada provides a more rigorous set of capabilities at the language level here, which doesn't help you, but you could figure out how these Ada requirements have been implemented in Linux. The Ada language spec is unique in providing a rationale document, see the section on real-time preemptive abort as a departure point.

You can either use threads, or have the function poll a timer (or a global variable set by SIGALRM handler), then save its state and exit when the allotted time has expired. Use of ucontext_t is deprecated and should never be used in new code, at all, much less from signal handlers.

The solution I desire suddenly occurs to me: goto! I'll setup a jump point just after the function I wish to limit, set a timer and in the signal handler which deals with the SIG*ALRM simply jump to the instruction after the function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!