为什么 GetProcessImageFileName 返回 null 而不是进程的地址

Why does GetProcessImageFileName return null instead of the address of the process?

本文关键字:进程 地址 GetProcessImageFileName 返回 null 为什么      更新时间:2023-10-16

我正在尝试汇集Qt中所有进程的列表。以下代码演示了我到目前为止的努力:

QList<QString> frmProcess::GetAllRunningProcesses()
{
    HANDLE hSysSnapshot = NULL;
    HANDLE processHandle;
    PROCESSENTRY32 proc;

    proc.dwSize = sizeof(proc);
    hSysSnapshot = CreateToolhelp32Snapshot ( TH32CS_SNAPPROCESS, 0 );
    Process32First(hSysSnapshot,&proc);
    proc.dwSize = sizeof(proc);
    ui->listWidget->clear();
    LPWSTR processPath;
    list.clear();
    do
    {
        //This block of code is to get each process's path and store it in a list
        //PROCESS_ALL_ACCESS is commented out since it fails the program on start-up
        processHandle = OpenProcess( /*PROCESS_ALL_ACCESS*/PROCESS_QUERY_INFORMATION |
                                PROCESS_VM_READ,
                                FALSE, proc.th32ProcessID );
        GetProcessImageFileName(processHandle,processPath,MAX_PATH);
        procpaths.append(QString::fromWCharArray(processPath));
        list.append(QString::fromWCharArray(proc.szExeFile));
    } while(Process32Next(hSysSnapshot,&proc));
    CloseHandle( hSysSnapshot );
    return list;
}

在上面发布的代码中,我正在尝试获取尽可能多的有关进程的信息,为此,我在CreateToolhelp32Snapshot的帮助下汇集进程名称,然后通过GetProcessImageFileName获取它们的路径。所有这些都发生在每毫秒的计时器时钟周期事件中。
如果我运行该程序,几秒钟后它崩溃了,我得到分段错误。
我也尝试了调试,因为我无法获得与任何进程相关的任何路径!
令我惊讶的是,我只得到每个进程路径的空字符串!我做错了什么?

您的GetProcessImageFileName没有收到正确的参数。 processPath必须指向有效的缓冲区。

TCHAR processPath[MAX_PATH] = { 0 };
GetProcessImageFileName(processHandle, processPath, _countof(processPath));

此外,您要检查返回的值以查看是否成功。