JChan
JChan

Reputation: 1451

How to check if a process is running or not using C++

I should not display certain context menu options if one process is not running?. I am checking if the process is running or not using the process name.

But the issue is, the process name is showing different way in different windows platforms.

ie, windows 64 bit process name on windows task bar is " applicationname.exe"

some windows xp machine shows the same process name as "applica~2.exe"

Please let me know the consistent way to check if the process is running or not?

My development environment is C++ and Visual Studio 2010

   DWORD getProcessID(const std::wstring& processName)
   {
       PROCESSENTRY32 info;
       info.dwSize = sizeof(info);

       HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
       if ( snapshot == INVALID_HANDLE_VALUE )
             return 0;

       Process32First(snapshot, &info);
       if ( !processName.compare(info.szExeFile) )
       {
             CloseHandle(snapshot);
             return info.th32ProcessID;
       }

       while ( Process32Next(snapshot, &info) )
       {
              if ( !processName.compare(info.szExeFile) )
               {
                    CloseHandle(snapshot);
                    return info.th32ProcessID;
               }
       }

      CloseHandle(snapshot);
     return 0;
   }

Upvotes: 3

Views: 4974

Answers (3)

Steve Townsend
Steve Townsend

Reputation: 54128

Using WMI to interrogate instances of Win32_Process allows you to check the fullpath of the running processes for a match on the one you need to see.

Upvotes: 1

Component 10
Component 10

Reputation: 10477

Are you the author of the process in question? If so, a more robust design would be to use IPC to interrogate the process directly. That way, you don't necessarily have to poll and you don't have irritating issues such as what happens if you detect the process, create the context menu and then the process goes down?

Upvotes: 0

lazy_banana
lazy_banana

Reputation: 460

EnumProcesses is the other way to enumerate active processes.

The difference is that you need to allocate the space for PIDs,call EnumProcesses, open each process with PROCESS_QUERY_INFORMATION access flag and then call GetProcessImageFileName on it's handle and do the comparison.

Upvotes: 2

Related Questions