MFC GetLastError返回5(拒绝访问)

时间:2014-05-27 07:41:55

标签: c++ mfc

我正在构建MFC Dialog Application 我使用Visual Studio 2010,MFC 2008/2010 在我的cpp文件中,我有一些代码来获取进程的信息。进程用户名为SYSTEM

HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
        PROCESS_VM_READ,
        FALSE, 0); // 0 is my process id
    DWORD testerror = GetLastError();
    // Get the process name.

    if (NULL != hProcess )
    {
        HMODULE hMod;
        DWORD cbNeeded;

        if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), 
            &cbNeeded) )
        {
            GetModuleBaseName( hProcess, hMod, namestr, 
                sizeof(namestr)/sizeof(TCHAR) );
        }
    }
    else 
    {
        MessageBox(L"", L"", MB_OK);
    }
    CloseHandle();

结果显示MessageBox,因为句柄为NULL 我得到GetLastError()并返回5(访问被拒绝) 我不知道为什么?非常感谢!

1 个答案:

答案 0 :(得分:1)

system idle process和其他一些系统进程不允许获取其信息。

系统空闲进程(ID 0)包含在名为[System Process]的快照中,您无法打开它的句柄,因为OpenProcess的文档特别说:

If the specified process is the System Process (0x00000000), the function fails and the last error code is ERROR_INVALID_PARAMETER. If the specified process is the Idle process or one of the CSRSS processes, this function fails and the last error code is ERROR_ACCESS_DENIED because their access restrictions prevent user-level code from opening them.