DuplicateHandle 伪句柄 与 实句柄的应用

如果把GetCurrentThread()返回值传递给一个HANDLE句柄,用它进行ResumeThread,结果肯定不是我们想要的。下面的例子详细描述了伪句柄的调用结果:

#include "stdafx.h" 
#include <stdio.h> 
#include <iostream> 
#include <windows.h> 
#include <process.h> 
using namespace std; 
#pragma warning(disable:4996) 
HANDLE hThread = NULL; 
unsigned int __stdcall ProcessInfo(void* lp) 
{ 
	string str = *(string*)lp; 
	delete lp; 
	hThread = GetCurrentThread(); 
	while(true){ 
		SuspendThread(GetCurrentThread()); 
		cout<<str.c_str()<<endl; 
	} 
	_endthreadex(0); 
	return 0; 
} 
int _tmain() 
{ 
	string *pStr = new string; 
	*pStr = "老婆, I Love You"; 
	unsigned int dwThreadID; 
	SECURITY_ATTRIBUTES sa; 
	sa.bInheritHandle = FALSE; 
	sa.lpSecurityDescriptor = NULL; 
	sa.nLength = sizeof(SECURITY_ATTRIBUTES); 
	HANDLE hCom = (HANDLE)_beginthreadex(&sa, 0, ProcessInfo, (void*)pStr, 0, &dwThreadID); 
	Sleep(1000);//线程肯定会先执行到SuspendThread,主线程一直在延时,并且全局hThread得到线程的伪句柄
	ResumeThread(hThread); 
	printf("hThread的句柄值是: %d\n", hThread); 
	Sleep(INFINITE); 
	CloseHandle(hCom); 
	return 0; 
}

结果显示,hThread是-2,线程没有输出任何东西


修改代码如下:

#include "stdafx.h" 
#include <stdio.h> 
#include <iostream> 
#include <windows.h> 
#include <process.h> 
using namespace std; 
#pragma warning(disable:4996) 
HANDLE hThread = NULL; 
unsigned int __stdcall ProcessInfo(void* lp) 
{ 
	string str = *(string*)lp; 
	delete lp; 
	DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), 
		&hThread, 0, 0, DUPLICATE_SAME_ACCESS); 
	while(true){ 
		SuspendThread(GetCurrentThread()); 
		cout<<str.c_str()<<endl; 
	} 
	_endthreadex(0); 
	return 0; 


} 
int _tmain() 
{ 
	string *pStr = new string; 
	*pStr = "老婆, I Love You"; 
	unsigned int dwThreadID; 
	SECURITY_ATTRIBUTES sa; 
	sa.bInheritHandle = FALSE; 
	sa.lpSecurityDescriptor = NULL; 
	sa.nLength = sizeof(SECURITY_ATTRIBUTES); 
	HANDLE hCom = (HANDLE)_beginthreadex(&sa, 0, ProcessInfo, (void*)pStr, 0, 
		&dwThreadID); 
	Sleep(1000);//线程肯定会先执行到SuspendThread,主线程一直在延时,并且全局hThread得到线程的伪句柄
		ResumeThread(hThread); 
	printf("hThread的句柄值是: %d\n", hThread); 
	Sleep(INFINITE); 
	CloseHandle(hCom); 
	return 0; 
} 

运行正常
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值