我在c中用 OpenProcess
打开一个进程,但是在得到它之后我无法使用它,因为我得到了"Invalid handle error" . 我知道正确的句柄,因为当我在这个句柄上执行 GetProcessId
时,它给了我正确的PID . 这就是我打开这个过程的方式 .
#include <windows.h>
#include <stdio.h>
#include <dbghelp.h>
#pragma (lib, "dbghelp.lib");
bool EnablePrivilege(LPCTSTR lpszPrivilegeName, BOOL bEnable)
{
HANDLE hToken;
TOKEN_PRIVILEGES tp;
LUID luid;
bool ret;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_READ, &hToken))
return FALSE;
if (!LookupPrivilegeValue(NULL, lpszPrivilegeName, &luid))
return FALSE;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
ret = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
CloseHandle(hToken);
return ret;
}
void main()
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
STARTUPINFOA startInfo;
PROCESS_INFORMATION processInfo;
ZeroMemory( &startInfo, sizeof(startInfo) );
startInfo.cb = sizeof(startInfo);
ZeroMemory( &processInfo, sizeof(processInfo) );
DWORD creationFlags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
const char* comLine = "Some process path and name";
// Start the child process.
if( CreateProcessA( NULL, // No module name (use command line)
(LPSTR)comLine, //argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
creationFlags, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&startInfo, // Pointer to STARTUPINFO structure
&processInfo ) // Pointer to PROCESS_INFORMATION structure
== false )
{
printf("FAIL!");
return;
}
SetLastError(0);
bool ok = SymInitialize(processInfo.hProcess, NULL, true);
int err = GetLastError();
}
由于某种原因,最后的错误值是垃圾 .
有没有办法检查过程句柄是否可以使用?
1 回答
从问题中的函数文档:
这意味着如果函数成功,你已经获得了一个可用的句柄,即无论你是否得到它,都没有"you have to wait"可以使用的中间点 . 在您的特定情况下,您的句柄可能无效,即函数失败 . 你在检查NULL的返回值吗?你用GetLastError()来看看发生了什么?