挂钩线程的创建/终止 [英] Hooking thread creation/termination

查看:79
本文介绍了挂钩线程的创建/终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Windows上挂入线程终止? IOW,如果进程内的一个线程(对其他进程及其线程不感兴趣)已终止(通常是-或更重要的是-强制终止),我想得到通知.

Is it possible to hook into thread termination on Windows? IOW, I would like to be notified if a thread inside the process (not interested in other processes and their threads) has terminated (either normally or - more important - forcefully).

或者,也可以加入线程创建.

Alternatively, hooking into thread creation would also do.

建议:我有一个基于每个线程管理一些信息的库(可以将其视为某些信息的整个进程的每个线程缓存).当线程终止时,我必须从缓存中删除所有特定于线程的信息. [使用线程ID实现缓存关联,该ID可能会在以后的线程中重复使用.]

Rationale: I have a library that manages some information on per-thread basis (think of it as a process-wide per-thread cache for some information). When a thread is terminated I have to remove all thread-specific information from the cache. [Cache associations are implemented using thread ID which may get reused for future threads.]

正常"执行顺序没有问题,因为库用户将从库中分离当前线程,这将清除状态.如果有人杀死拥有缓存资源的线程,就会开始出现问题.

There's no problem with "normal" execution order as the library user will detach the current thread from the library which will clear the state. Problems start to appear if somebody kills the thread owning cached resource.

推荐答案

您可以使用 TerminateThread .

You could use something like Detours to do API-level hooking of Win32 APIs like TerminateThread.

不过,我不明白您为什么需要这样做.听起来好像您需要在线程死亡时清除该线程的关联缓存,以便在出现另一个具有相同ID的线程时可以重新使用该插槽.这是正确的吗?

I'm not seeing why you need to do this, though. It sounds like you need to clear the thread's associated cache when the thread dies so you can re-use that slot if another thread with the same ID comes along. Is this correct?

如果是这样,当您收到DLL_THREAD_ATTACH事件时,是否不能仅清除DllMain中的缓存关联?这实际上是您的新线程通知.此时,您知道您有一个新线程,那么清除现有的关联缓存不是安全的吗?

If so, couldn't you just clear the cache association in DllMain when you get the DLL_THREAD_ATTACH event? This is essentially your new thread notification. At this point, you know you have a new thread, so isn't it safe to clear the existing associated cache?

另一个可行的替代方法是线程本地存储(TLS).您可以使用Win32 API,例如 TlsAlloc / TlsSetValue 来存储特定于线程的信息.您还可以使用 __declspec(thread) 让编译器为您管理TLS.这样,每个线程都维护自己的缓存.每个线程的代码都相同,但是数据访问是相对于线程而言的.

The other alternative that might work is thread-local storage (TLS). You can use Win32 APIs like TlsAlloc/TlsSetValue to store thread-specific information. You could also define a variable with __declspec(thread) to have the compiler manage the TLS for you. This way, each thread maintains its own cache. The code remains the same for each thread, but the data accesses are relative to the thread.

这篇关于挂钩线程的创建/终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆