winapi - Process32Next 因 ERROR_INSUFFICIENT_BUFFER 而失败(Windows 7)

标签 winapi visual-c++ process

我正在尝试获取正在运行的进程的所有可执行路径的列表

do-while 循环(如下所示)开始并在大约 90 次迭代后失败并出现 ERROR_INSUFFICIENT_BUFFER 错误。我想这就是 pBuffer,我尝试了一个非常大的缓冲区,但仍然失败。失败迭代的 ProcessEntry 结构在 szExeFile 中有垃圾。请指教(我关闭了句柄,下面没有显示)

代码:

// Retrieve a handle to the process snapshot
HANDLE hProcessSnapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
if (INVALID_HANDLE_VALUE == hProcessSnapshot) ERROR;

// Retrieve information about the first process and exit if unsuccessful
PROCESSENTRY32 oProcessEntry;
memset(&oProcessEntry, 0x00, sizeof(oProcessEntry));
oProcessEntry.dwSize = sizeof(PROCESSENTRY32);
BOOL bFileFound(Process32First(hProcessSnapshot, &oProcessEntry));
DWORD dwError;
if(!bFileFound) {        
    dwError = GetLastError();
    if(ERROR_NO_MORE_FILES == dwError) return TPathList();

    // Error
    ERROR; 
}

// Walk the snapshot of processes
TCHAR pBuffer[MAX_PATH];
TPathList lExecutablePaths;
do {
    // Get handle to process
    HANDLE hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 
                                FALSE, 
                                oProcessEntry.th32ProcessID));
    if(INVALID_HANDLE_VALUE == hProcess) ERROR;
    if (!hProcess) continue;

    // Get the module path
    if(GetModuleFileNameEx(hProcess, 0, pBuffer, MAX_PATH) == 0) ERROR;      
    lExecutablePaths.push_back(CPath(pBuffer));        
} 
// Get next process 
while(Process32Next(hProcessSnapshot, &oProcessEntry));

// If we ran out of files return what has been found
dwError = GetLastError();
if(ERROR_NO_MORE_FILES == dwError) return lExecutablePaths;
ERROR;

最佳答案

你可以这样使用:

CString sBuffer;
DWORD dwSize = MAX_PATH + 1, dwError = 0;

do
{
    GetModuleFileName( NULL, sBuffer.GetBuffer( dwSize ), dwSize );

    // Retrieve the last error. If we've succeeded ERROR_SUCCESS
    // will be returned; otherwise, we'll get an ERROR_INSUFFICIENT_BUFFER
    // error.
    dwError = ::GetLastError( );

    // Buffer may not be big enough so double its size
    dwSize *= 2;
}
while( dwError == ERROR_INSUFFICIENT_BUFFER
    && dwError != ERROR_SUCCESS );

// Release the buffer (turn the string back to const)
sBuffer.ReleaseBuffer( );

我希望它能奏效。

您也可以选择 How can I calculate the complete buffer size for GetModuleFileName?

关于winapi - Process32Next 因 ERROR_INSUFFICIENT_BUFFER 而失败(Windows 7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10875966/

相关文章:

c++ - 这被认为是硬编码吗?

c++ - 将源代码从 Visual C++ 移植到 GCC 的陷阱是什么

c++ - 当我终止进程时,它也会终止线程吗?

javascript - 如何判断子 Node.js 进程是否来自 fork()?

delphi - 如何对特定 HID 设备执行硬件重置?

winapi - 从 tagRECT/CRect 转换为 Gdiplus::Rect

c++ - 如何将 PEM 格式的公钥转换为 CNG key blob?

c - 多个原始输入缓冲区

c++ - 是否可以在编译 Debug 项目时指示 MSVC 使用 Boost 的发布版本?

PHP exec() 不存储进程 ID