GetCurrentProcess() 原型如下:
[Plain Text] 纯文本查看 复制代码 HANDLE WINAPI GetCurrentProcess(void);
函数没有参数,返回值是当前进程的虚句柄。
一个虚句柄是一个特别的常数,对于目前来说,值为 -1 ,也就是说如果将 -1 当成是一个句柄,那么就表示当前进程的句柄。为了能和以后的操作系统兼容,我们最好还是用 GetCurrentProcess() 函数来获取本进程的句柄,而不是直接使用这个硬编码。任何时候需要当前进程的句柄时,都可以该函数获得。虚句柄不能由子进程继承。
虚句柄对于进程对象来说具有 PROCESS_ALL_ACCESS 访问权限。
一个进程可以在在其他进程的上下文环境里给自己创建一个真实的句柄,如使用 OpenProcess() 函数就可以做到这一点。
测试代码:
[C++] 纯文本查看 复制代码 #include "stdafx.h"
#include "stdafx.h"
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
printf ("My PID is %d\n", GetCurrentProcessId());
printf ("my Handle is %d\n", GetCurrentProcess());
HANDLE hMyselfHandle = OpenProcess (PROCESS_ALL_ACCESS, TRUE, GetCurrentProcessId());
printf ("Get my PID through My real handle: %d\n", GetProcessId(hMyselfHandle));
return 0;
}
运行输出:My PID is 6540
my Handle is -1
Get my PID through My real handle: 6540 程序中,GetProcessId() 函数可以通过句柄获得进程的 PID 。由输出可见,在进程为自己创建了真实的句柄后,由此所获得的 PID 值和直接使用 GetCurrentProcessId() 是一致的。
此外,虚句柄最后也不需要用 CloseHandle() 函数进行句柄关闭。 |