如果把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;
}
运行正常
版权声明:本文为博主原创文章,未经博主允许不得转载。
转载于:https://www.cnblogs.com/qq76211822/p/4712042.html
今天的文章DuplicateHandle 伪句柄 与 实句柄的应用分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/9302.html