Home > database >  Get Name List of all running processes windows
Get Name List of all running processes windows

Time:09-16

I want to get list of all running processes like following

example.exe
example2.exe

so on... heres code what ive tried

WCHAR* GetAllRunningProccess()
{
    PROCESSENTRY32 pe32;
    HANDLE snap = CreateToolhelp32Snapshot(
        TH32CS_SNAPPROCESS, 0
    );

    pe32.dwSize = sizeof(PROCESSENTRY32);

    Process32First(snap, &pe32);

    do {
        return  pe32.szExeFile;
    } while (Process32Next(snap, &pe32));
}
    std::wcout << GetAllRunningProccess() << std::endl;

it only prints

[System Process]

CodePudding user response:

The code you have written does not work like a generator function to yield multiple values. It just exits when returning the first value. You cannot return from a function more than once.

do {
   return ...; // This will both exit the loop and exit the function.
} while(...);

Although, coroutines offer co_yield to accomplish this.

To fix...

The most basic repair would be to redesign your function to return a vector of strings rather than just a single string.

std::vector<std::string> GetAllRunningProcesses()
{
    PROCESSENTRY32 pe32;
    HANDLE snap = CreateToolhelp32Snapshot(
        TH32CS_SNAPPROCESS, 0
    );

    pe32.dwSize = sizeof(PROCESSENTRY32);

    Process32First(snap, &pe32);

    std::vector<std::string> result;
    do {
        result.push_back(pe32.szExeFile);
    } while (Process32Next(snap, &pe32));
    CloseHandle(snap);
    return result;
}

Then, to call it, you could use something like this:

for (const auto& processName : GetAllRunningProcesses()) {
   std::cout << processName << std::endl;
}

CodePudding user response:

In your code

do {
        return  pe32.szExeFile;
    } while (Process32Next(snap, &pe32));

Am pretty sure after executing this while loop once the compiler is returning one value then exiting the function and continues executing the code in main body rather then going back to the loop, hence getting only 1 output(one process).

Update your Code accordingly and then test.

  •  Tags:  
  • c
  • Related