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; 
} 


运行正常

版权声明:本文为博主原创文章,未经博主允许不得转载。

 

posted @ 2015-01-16 11:43  QQ76211822  阅读(515)  评论(0编辑  收藏  举报