如何在 sem_timedwait 中管理 EINTR errno

发布于 2024-09-28 08:01:52 字数 326 浏览 3 评论 0原文

你能帮助我理解为什么建议使用:

while ((s = sem_timedwait(&sem, &ts)) == -1 && errno == EINTR)
    continue; // Restart when interrupted by handler

(EINTR:调用被信号处理程序中断)

而不是简单地:

s = sem_timedwait(&sem, &ts);

在巫术情况下我必须管理 EINTR ?

Can you help me to understand why it is recommended to use:

while ((s = sem_timedwait(&sem, &ts)) == -1 && errno == EINTR)
    continue; // Restart when interrupted by handler

(EINTR: The call was interrupted by a signal handler)

Instead of simply:

s = sem_timedwait(&sem, &ts);

In witch cases I have to manage EINTR ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

辞取 2024-10-05 08:01:52

如果在系统调用执行期间捕获到信号,则循环将导致系统调用重新启动,因此除非系统调用成功或失败(有其他错误),否则循环不会继续执行下一条语句。否则,当系统调用被信号处理程序中断时,线程将继续执行下一条语句。

例如,如果您希望能够通过向线程发送特定信号来中止此sem_timedwait(),那么您不希望无条件重新启动系统调用。相反,您可能想要标记操作已中止并清理。如果您有多个信号处理程序,信号处理程序可以设置一个标志,当遇到 EINTR 时可以检查该标志,以确定是否重新启动系统调用。

仅当线程使用信号处理程序捕获任何信号,并且 sigaction() SA_RESTART 标志未用于自动重新启动任何中断的系统调用时,这才有意义。但是,如果您没有使用任何信号处理程序并且不希望您的代码受到信号处理程序的影响,那么使用循环仍然是一个很好的做法,这样即使您的代码稍后运行,它也将继续按您的预期工作。与使用信号处理程序用于不相关目的的其他代码在同一程序中使用。

The loop will cause the system call to be restarted if a signal is caught during the execution of the system call, so it will not go on to the next statement unless the system call has either succeeded or failed (with some other error). Otherwise the thread will continue execution with the next statement when the system call is interrupted by a signal handler.

For example, if you want to be able to abort this sem_timedwait() by sending a particular signal to the thread, then you would not want to unconditionally restart the system call. Instead you may want to mark that the operation was aborted and clean up. If you have multiple signal handlers, the signal handler can set a flag which can be checked when EINTR is encountered in order to determine whether to restart the system call.

This only matters if the thread catches any signals using a signal handler, and the sigaction() SA_RESTART flag was not used to automatically restart any interrupted system call. However, if you are not using any signal handlers and did not intend for your code to be affected by a signal handler, it is still good practice to use the loop so that it will continue to work as you intended even if your code is later used in the same program as other code which uses signal handlers for unrelated purposes.

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