Windows Hooks 的 Linux 等效项

发布于 2024-12-13 04:17:15 字数 317 浏览 0 评论 0原文

我想知道如何表达类似 Windows 挂钩 在Linux中。

我有一个带有各种线程的 Linux 应用程序。主线程当前为 ctrlc 安装了一个信号处理程序,捕获它并关闭应用程序。

我希望应用程序中的另一个线程首先处理 ctrlc 事件,然后传递到主线程。

I would like to know how to express something like a windows hook
in Linux.

I have a Linux application with various threads. The main thread currently installed a signal handler for ctrlc, catches it and shuts down the application.

I would like another thread in the application to process the ctrlc event first and then pass on to the main thread.

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

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

发布评论

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

评论(2

走过海棠暮 2024-12-20 04:17:15

据我所知,这很难做到。 Unix 信号是原始的。

默认情况下,信号被传递到随机线程。为了解决这个问题,通常采用的技巧是阻止除一个线程之外的所有线程中的信号。最简单的方法是使用 pthread_sigmask 阻止 main 中的所有信号,然后创建线程(它将继承信号掩码),然后使用一个单独的线程来执行 sigwait /sigwaitinfo 阻止信号。这会强制将信号传递到该线程。

在信号捕获线程中消耗信号后,您需要使用 main 的线程 id 和捕获的信号编号执行 pthread_kill 以将信号转发到 main。问题是 main 会被阻塞。

在转发信号之前,您无法真正解除阻塞 main 并阻塞信号捕获线程,因为这是一种竞争条件 - 没有什么可以阻止第二个信号进入,并且信号捕获线程看不到它。这一切的努力都白费了。

您可以让信号线程通过某种其他形式的 IPC(管道或其他形式)向 main 发送一条消息,说“捕获 XX,采取适当的操作”。也许这就足够了?

也许有人有一些聪明的想法,但我怀疑底线是这不是 UNIX 中通常的做法。

As far as I know this would be tricky to do. Unix signals are primitive.

Signals get delivered to a random thread by default. To get around this the trick usually employed is to block signals in all the threads except one. The easiest way to do this is to block all the signals in main with pthread_sigmask, then create the threads (which will inherit the signal mask), and then have a separate thread that does a sigwait/sigwaitinfo on the blocked signals. This forces the signals to be delivered to that thread.

After consuming the signal in the signal-catching thread you would need to do a pthread_kill with main's thread id and the caught signal number to forward the signal to main. The problem is that main would have it blocked.

You can't really unblock main and block the signal-catching thread before forwarding the signal because it is a race condition - there is nothing stopping a second signal from coming in and the signal-catching thread not seeing it. That defeats the whole effort.

You could have the signal-thread send a message to main through some other form of IPC (pipe or whatever) saying "caught XX, take appropriate action". Maybe that is sufficient?

Maybe someone has some clever idea but I suspect the bottom line is that this just isn't how it is normally done in unix.

热风软妹 2024-12-20 04:17:15

另一个技巧(由Qt文档建议)可能是有一个信号处理程序将(例如单个字节)写入管道,并有一些线程,pr 只是一些事件处理程序(例如 g_io_add_watch 与 GTK)句柄字节。

Another trick (suggested by Qt documentation) could be to have a signal handler writing (e.g. a single byte) into a pipe, and have some thread, pr just some event handler (e.g. g_io_add_watch with GTK) handle the byte.

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