PIDMap ProcessHandleCache::CleanupMap() { PIDMap removePids; for (auto i = m_cache.begin(); i != m_cache.end(); ++i) { DWORD exitcode = 0; BOOL result = GetExitCodeProcess(i->second.get(), &exitcode); if (result == FALSE || exitcode != STILL_ACTIVE) { DWORD pid = i->first; removePids[pid] = std::move(i->second); } } for (auto i = removePids.begin(); i != removePids.end(); ++i) m_cache.erase(i->first); return removePids; }
DWORD SelectProcess() { PIDMap pids; int len = sizeof(lookingProcessName) / sizeof(std::string); for (int i = 0; i < len; ++i) GetProcessIDsByName(pids, lookingProcessName[i]); if (pids.empty()) { printf("process NOT found.\n"); system("pause"); return 0; } // just one PID found else if (pids.size() == 1) { // we already know it's not empty so we can do this safely DWORD processID = pids.begin()->first; std::string processName = pids.begin()->second; printf("%s process found, PID: %u\n", processName.c_str(), processID); // checks this process is already injected or not if (IsProcessAlreadyInjected(processID, injectDLLName)) { printf("Process is already injected.\n\n"); system("pause"); return 0; } return processID; } // size > 1, multiple possible processes else { printf("Multiple processes found.\n"); printf("Please select one which will be injected.\n\n"); // stores the PIDs which are already injected // so these are "invalid" PIDMap injectedPIDs; unsigned int idx = 1; for (PIDMap::const_iterator itr = pids.begin(); itr != pids.end(); ++itr) { DWORD pid = itr->first; printf("[%u] PID: %u\n", idx++, pid); if (IsProcessAlreadyInjected(pid, injectDLLName)) { printf("Already injected!\n\n"); injectedPIDs[pid] = itr->second; } } // same size: there is no non-injected PID if (pids.size() == injectedPIDs.size()) { printf("All the processes are already injected.\n\n"); system("pause"); return 0; } unsigned int selectedIndex = 0; // loops until has correct PID while (1) { DWORD processID = 0; selectedIndex = 0; printf("Please select a process, use [index]: "); scanf("%u", &selectedIndex); // bigger than max index if (selectedIndex > idx - 1) { printf("Your index is too big, max index is %u.\n", idx - 1); continue; } // 0 or non int used else if (selectedIndex == 0) { printf("Your index is invalid, 1-%u should be used.\n", idx - 1); continue; } // gets PID via index PIDMap::const_iterator itr = pids.begin(); std::advance(itr, selectedIndex - 1); processID = itr->first; // if already injected if (injectedPIDs.find(processID) != injectedPIDs.end()) { printf("This process is already injected. "); printf("Please choose a different one.\n"); continue; } printf("\n"); // looks like all good return processID; } } return 0; }