GetCurrentThread() returns pseudo handle, not the real handle.

本文介绍了在Windows API中GetCurrentThread返回的伪句柄及其潜在问题。伪句柄实际上指向调用该函数的当前线程。若将此句柄传递给其他线程并用于操作,可能会导致误操作调用线程本身。文章通过示例说明了如何使用DuplicateHandle函数创建真实句柄。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

From: http://weseetips.com/tag/pseudo-handle/

For getting our thread handle, we usually call GetCurrentThread() api. But actually it returns a pseudo handle. A pseudo handle, is a special handle which represents the handle of current thread which uses it. Please see the following e.g. for more clarify.

1) Thread A gets its threadID by calling GetCurrentThread and Passed to Thread B.
2) Thread B needs to terminate Thread A. So it calls TerminateThread( handle passed by Thread A ).
3) But instead of terminating Thread A, Thread B will be terminated, because the handle passed by Thread A was pseudo and it will become Thread B’s handle when Thread B uses it.

Debug one GetCurrentThread() call and GetCurrentProcess() call and watch its return values. You can see what they returns are follows,

  • GetCurrentThread() –  0xfffffffe
  • GetCurrentProcess() –  0xffffffff

Ofcourse pseudo… isn’t it ?

Icon How Can I Do It?
For getting a real handle which represents your thread, create a duplicate handle by calling DuplicateHandle(). Please see the code block below.

HANDLE hRealHandle = 0;
DuplicateHandle( GetCurrentProcess(), // Source Process Handle.
                 GetCurrentThread(),  // Source Handle to dup.
                 GetCurrentProcess(), // Target Process Handle.
                 &hRealHandle,        // Target Handle pointer.
                 0,                   // Options flag.
                 TRUE,                // Inheritable flag
                 DUPLICATE_SAME_ACCESS );// Options
// Now the hRealHandle contains a real handle for your thread.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值