检查给定进程是否正在运行

Checking if given process is running

本文关键字:运行 是否 进程 检查      更新时间:2023-10-16

当我使用以下函数作为isRunning("example.exe")时;无论进程是否正在运行,它总是返回0。

我尝试将其设置为std::cout<<pe.szExeFile;在do-while循环中,它以与我尝试传递函数相同的格式输出所有进程。

该项目是多字节字符集,以防万一。

bool isRunning(CHAR process_[])
{
    HANDLE pss = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
    PROCESSENTRY32 pe = { 0 };
    pe.dwSize = sizeof(pe);
    if (Process32First(pss, &pe))
    {
        do
        {
            if (pe.szExeFile == process_)  // if(!strcmp(pe.szExeFile, process_)) is the correct line here
                return true; // If you use this remember to close the handle here too with CloseHandle(pss);
        } while (Process32Next(pss, &pe));
    }
CloseHandle(pss);
return false;
}

似乎找不到我的错误。谢谢你的时间。

您正在使用比较指针值的if (pe.szExeFile == process_)。 您应该使用 strcmp_stricmp 之类的东西来比较实际的字符串值。

例如

if(strcmp (pe.szExeFile, process_) == 0)
  return true;