#include <TlHelp32.h>
#include <process.h>
/**
* 检查是否已加载目标dll
* @param pid
* @param dll
* @return TCHAR* 带全路径的dll -- 不为NULL时,用完要释放返回结果
*/
TCHAR* ProcessHasLoadDll(DWORD pid, const TCHAR* dll) {
/*
* 参数为TH32CS_SNAPMODULE 或 TH32CS_SNAPMODULE32时,如果函数失败并返回ERROR_BAD_LENGTH,则重试该函数直至成功
* 进程创建未初始化完成时,CreateToolhelp32Snapshot会返回error 299,但其它情况下不会
*/
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);
while (INVALID_HANDLE_VALUE == hSnapshot) {
DWORD dwError = GetLastError();
if (dwError == ERROR_BAD_LENGTH) {
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);
continue;
} else {
if (dwError == ERROR_PARTIAL_COPY) {
MYLOG4CXX_DEBUG(logger, TEXT("CreateToolhelp32Snapshot failed ") << dwError << " currentProcessId: " << GetCurrentProcessId() << " targetProcessId: " << pid);
}
else {
MYLOG4CXX_ERROR(logger, TEXT("CreateToolhelp32Snapshot failed ") << dwError << " currentProcessId: " << GetCurrentProcessId() << " targetProcessId: " << pid);
}
return NULL;
}
}
MODULEENTRY32 mi;
mi.dwSize = sizeof(MODULEENTRY32); //第一次使用必须初始化成员
BOOL bRet = Module32First(hSnapshot, &mi);
while (bRet) {
// mi.szModule是短路径
if (wcsstr(dll, mi.szModule) || wcsstr(mi.szModule, dll)) {
TCHAR* dllWithFullPath = new TCHAR[MAX_MODULE_NAME32 + 1];
lstrcpy(dllWithFullPath, mi.szModule);
CloseHandle(hSnapshot);
return dllWithFullPath;
}
mi.dwSize = sizeof(MODULEENTRY32);
bRet = Module32Next(hSnapshot, &mi);
}
CloseHandle(hSnapshot);
return NULL;
}