Enumprocesses-怪异的行为
EnumProcesses - weird behaviour
本文关键字:Enumprocesses- 更新时间:2023-10-16
我在使用Windows API函数EnumProcesses((
时具有一些奇怪的行为我有一个函数可以确定一个已经在运行的过程已经在运行,而我可以手动打开。
当我通过shell打开它时,它仅检测到它的运行仅1次(本身(,一切都很好。当我使用.exe文件上的doubleclick打开它时
对于以下代码签名,请提及:
this->thisExecutableFile
包含argv [0](从运行程序中初始化(以获取自己的过程名称,如您所示:
int main(int argc, char* argv[])
{
ClientUpdate* update = ClientUpdate::getInstance();
update->setThisExecutableFile(argv[0]);
if (update->clientUpdateProcessIsRunning() == false) {
...
我的目标是找出此过程的另一个实例是否已经在运行,在这种情况下将退出。
这是我的代码:
bool ClientUpdate::clientUpdateProcessIsRunning()
{
bool retVal = false;
uint16_t processCount = 0;
unsigned long aProcesses[1024], cbNeeded, cProcesses;
if(!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
return false;
cProcesses = cbNeeded / sizeof(unsigned long);
for(unsigned int i = 0; i < cProcesses; i++) {
if (aProcesses[i] == 0) {
continue;
}
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, aProcesses[i]);
wchar_t buffer[50];
GetModuleBaseNameW(hProcess, 0, buffer, 50);
CloseHandle(hProcess);
std::wstring tempBuffer(buffer);
std::string tempStringBuffer(tempBuffer.begin(), tempBuffer.end());
boost::filesystem::path p(this->thisExecutableFile);
if(_strcmpi(p.filename().string().c_str(), tempStringBuffer.c_str()) == 0) {
processCount++;
if(processCount > 1) {
retVal = true;
break;
}
}
}
return retVal;
}
我知道,在文件上使用doubleclick或通过shell调用doubleclick时,基本路径是不同的。(shell仅产生文件名,而doubleclick将整个路径 文件名传递到argv [0](,但是我使用
解决了该问题boost::filesystem::path p(this->thisExecutableFile);
p.fileName()
在我使用Print检查的两种情况下返回正确的文件名(无路径(。
我很困惑为什么通过doubleclick而不是shell调用文件时,enumprocesses((两次将我返回相同的文件。它没有产卵两个处理,在Taskmanager中,我也看不到这样的东西。
这是一个错误,还是我需要了解我在文档中找不到的方法?
感谢Richard Critten的提示,我能够修复它。我的方法现在要小得多,而且更容易。(也可能比扫描整个Process-stack的性能也更多。(:D
这是解决方案
bool ClientUpdate::clientUpdateProcessIsRunning()
{
HANDLE hMutex = CreateMutexA(NULL, TRUE, "client-updater-mtx");
DWORD dwErr = GetLastError();
return dwErr == ERROR_ALREADY_EXISTS;
}
谢谢!