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

use*_*839 3 c++ winapi

当我使用以下函数作为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;
}
Run Code Online (Sandbox Code Playgroud)

似乎无法找到我的错误.谢谢你的时间.

edt*_*guy 5

您正在使用if (pe.szExeFile == process_)它比较指针值.您应该使用类似strcmp_stricmp比较实际字符串值的内容.

例如

if(strcmp (pe.szExeFile, process_) == 0)
  return true;
Run Code Online (Sandbox Code Playgroud)