Cesar
Cesar

Reputation: 379

How to count number of running process with given name?

How I could check how many instances of an executable is running also checking if each exe has a different PID?

--Edit-- What I already got:

The code display the PID correctly but szProcessName always return: enter image description here

void DisplayProcessNameAndID(DWORD processID)
{
    TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");

    // Get a handle to the process.  
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
        PROCESS_VM_READ,
        FALSE, processID);

    // Get the process name.  
    if (NULL != hProcess)
    {
        HMODULE hMod;
        DWORD cbNeeded;

        //Given a handle to a process, this returns all the modules running within the process.
        //The first module is the executable running the process,
        //and subsequent handles describe DLLs loaded into the process.
        if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
        {
            //This function returns the short name for a module,
            //typically the file name portion of the EXE or DLL
            GetModuleBaseName(hProcess, hMod, szProcessName,
                sizeof(szProcessName) / sizeof(TCHAR));
        }
    }

    // Display the process name and identifier.
    CString str;
    str.Format("Text:%s, PID : %u", szProcessName, processID);
    //AfxMessageBox(str);

    //close the process handle
    CloseHandle(hProcess);
}
void Processes()
{
    // Get the list of process identifiers.  
    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    //This returns a list of handles to processes running on the system as an array.
    if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
        return;

    // Calculate how many process identifiers were returned.  
    cProcesses = cbNeeded / sizeof(DWORD);

    // Display the name and process identifier for each process.  
    for (i = 0; i < cProcesses; i++)
        if (aProcesses[i] != 0)
            DisplayProcessNameAndID(aProcesses[i]);
}

Upvotes: 0

Views: 746

Answers (1)

Drake Wu
Drake Wu

Reputation: 7170

As mentioned in the comment, OpenProcess failed and the GetModuleBaseName function was skipped. The processes you opened are protected process. Even if you have the SeDebugPrivilege privilege, it can only allow PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE access.

The following sample to list process with name works for me: Taking a Snapshot and Viewing Processes. And I made some simple modifications to meet your needs:

int main(void)
{
    int count = GetProcessCount(TEXT("notepad.exe"));
    _tprintf(TEXT("The Number of process %s has %d instance \n"), TEXT("notepad.exe"), count);
    return 0;
}

BOOL GetProcessCount(const TCHAR* name)
{
    HANDLE hProcessSnap;
    HANDLE hProcess;
    PROCESSENTRY32 pe32;
    DWORD dwPriorityClass;
    int count = 0;
    // Take a snapshot of all processes in the system.
    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == INVALID_HANDLE_VALUE)
    {
        printError(TEXT("CreateToolhelp32Snapshot (of processes)"));
        return(FALSE);
    }

    // Set the size of the structure before using it.
    pe32.dwSize = sizeof(PROCESSENTRY32);

    // Retrieve information about the first process,
    // and exit if unsuccessful
    if (!Process32First(hProcessSnap, &pe32))
    {
        printError(TEXT("Process32First")); // show cause of failure
        CloseHandle(hProcessSnap);          // clean the snapshot object
        return(FALSE);
    }

    // Now walk the snapshot of processes, and
    // display information about each process in turn
    do
    {
        _tprintf(TEXT("\n\n====================================================="));
        _tprintf(TEXT("\nPROCESS NAME:  %s"), pe32.szExeFile);
        _tprintf(TEXT("\n-------------------------------------------------------"));

        _tprintf(TEXT("\n  Process ID        = 0x%08X"), pe32.th32ProcessID);
        if (_tcscmp(pe32.szExeFile, name) == 0)
            count++;

    } while (Process32Next(hProcessSnap, &pe32));

    CloseHandle(hProcessSnap);
    return count;
}


void printError(const TCHAR* msg)
{
    DWORD eNum;
    TCHAR sysMsg[256];
    TCHAR* p;

    eNum = GetLastError();
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, eNum,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        sysMsg, 256, NULL);

    // Trim the end of the line and terminate it with a null
    p = sysMsg;
    while ((*p > 31) || (*p == 9))
        ++p;
    do { *p-- = 0; } while ((p >= sysMsg) &&
        ((*p == '.') || (*p < 33)));

    // Display the message
    _tprintf(TEXT("\n  WARNING: %s failed with error %d (%s)"), msg, eNum, sysMsg);
}

Upvotes: 1

Related Questions