C ++检查特定进程是否正在运行

时间:2013-07-29 10:43:12

标签: c++

我正在编写一个C ++ DLL,需要检查特定进程是否正在运行。

将启动的应用程序将运行在:

c:\Directory\application.exe

其中有一个子目录,其中包含另一个可执行文件:

c:\Directory\SubDirectory\application2.exe

如果检查application2.exe正在运行,DLL运行时需要做什么,最重要的是它在该文件夹中运行 - 将运行多个副本,因此我们需要确保运行正确的副本

我有以下代码可以很好地检测到application2.exe正在运行,但它没有考虑文件路径:

HANDLE pss = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);   

PROCESSENTRY32 pe = { 0 };  
pe.dwSize = sizeof(pe);  

if (Process32First(pss, &pe))   
{  
 do  
 {  
   if(wcscmp(pe.szExeFile, L"application2.exe") == 0)
   {
       CloseHandle(pss);
       return (1);      
   }
 }  
 while(Process32Next(pss, &pe));  
}   

CloseHandle(pss);

如何检查进程的路径是否与调用DLL的应用程序的路径匹配?

2 个答案:

答案 0 :(得分:0)

使用WMI。

从命令行中可以执行以下操作:

wmic process where "executablepath = 'c:\path\to\executable.exe'" get ProcessId

您可以使用C ++中的WMI apis做类似的事情。

答案 1 :(得分:0)

我得到了一个适用于此的解决方案,以防其他人在此搜索:

HANDLE ProcessSnap;
PROCESSENTRY32 Pe32;
unsigned int LoopCounter = 0;

Pe32.dwSize = sizeof(PROCESSENTRY32);
ProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

Process32First(ProcessSnap, &Pe32);

wchar_t TermPath[MAX_PATH];
GetModuleFileName(NULL, TermPath, MAX_PATH);
wstring WTermPath(TermPath);

int index = WTermPath.find(L"\\application.exe");
wstring Path = WTermPath.substr(0, (index));
Path = Path + L"\\SubDirectory\\Application2.exe";

do
{
    HANDLE Process;
    wchar_t FilePath[MAX_PATH];

    Process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, Pe32.th32ProcessID);

    if (Process)
    {
        GetModuleFileNameEx(Process, 0, FilePath, MAX_PATH);
        wstring WFilePath(FilePath);
        if(WFilePath == Path)
        {
            CloseHandle(ProcessSnap);
            return (1);      
        }           
        CloseHandle(Process);
    }

    LoopCounter++;
} while (Process32Next(ProcessSnap, &Pe32));

CloseHandle(ProcessSnap);