无法获取进程的句柄

Cannot get handle of process

本文关键字:句柄 取进程 获取      更新时间:2023-10-16

解决:看看我的最后一篇文章。这可能是Windows XP和以前版本的GetProcessId函数所需权限的问题

没有生成错误。GetProcessId仍然返回0。我解决不了这个问题。

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <psapi.h> //For EnumProcessModules.
#include <tlhelp32.h>
#include <iostream>
using namespace std;
HANDLE GetHandleByName( string str )
{
    HANDLE hProcess = NULL;
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof( PROCESSENTRY32 );
    HANDLE snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL );
    if( Process32First( snapshot, &entry ) == TRUE )
    {
        while( Process32Next( snapshot, &entry ) == TRUE )
        {
            WCHAR* wchrstr = ( WCHAR * )malloc( 128 );
            mbstowcs ( wchrstr, str.c_str(), 128 );
            if( wcscmp( reinterpret_cast< const wchar_t * >( entry.szExeFile ), wchrstr ) == 0 )
            {
                hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID );
            }
            free( wchrstr );
         }
    }
    CloseHandle( snapshot );
    return hProcess;
}

void main()
{
    HANDLE hProcess = GetHandleByName( "System" );
    cout << GetProcessId( hProcess );
    cin.get();
}

首先,您是在尝试获取System进程还是[System Process]虚拟进程?无论哪种方式,您的代码都有一些必须解决的问题。

如果您只尝试System,那么您的代码只需进行一些小的调整即可工作。如果你真正想要的是[System Process],那么你就没有运气了。

首先,您不进行错误检查。也许CreateToohelp32Snapshot失败了,并且您在Process32First调用中使用了无效句柄。其次,调用Process32First,然后立即调用Process32Next,而不查看Process32First返回的进程。换句话说,您总是跳过返回的第一个进程。无独有偶,猜猜哪个进程是返回的第一个进程?它是虚拟的[System Process]

因此,让我们尝试一个枚举所有进程并正确执行的函数:

void EnumAllProcesses(BOOL bTryToOpen = FALSE,
                      DWORD dwAccess = PROCESS_QUERY_INFORMATION)
{
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof( PROCESSENTRY32 );
    HANDLE snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL );
    if( snapshot == INVALID_HANDLE_VALUE )
    {
        _tprintf(_T("Unable to create a ToolHelp32 snapshot (%08X)n"), GetLastError());
        return;
    }
    if( Process32First( snapshot, &entry ) == TRUE )
    {
        do
        {
            _tprintf(_T("Process: %s (%u)n"), entry.szExeFile, entry.th32ProcessID);
            if(bTryToOpen)
            {
                HANDLE hProcess = OpenProcess( dwAccess,
                                               FALSE, 
                                               entry.th32ProcessID );
                _tprintf(_T("    hProcess = %p (%08X)n"), hProcess, GetLastError());
                if(hProcess != NULL)
                    CloseHandle(hProcess);
            }
        } while( Process32Next( snapshot, &entry ) == TRUE );        
    }
    CloseHandle( snapshot );
}

但是,即使有了这个新代码,如果您想打开[System Process],也会遇到问题。原因是当您指定此进程的进程ID(恰好总是零)时,OpenProcess将与ERROR_INVALID_PARAMETER一起失败。这是记录的行为。查看CreateProcess上的MSDN页面,特别是dwProcessId参数解释:

如果指定的进程是系统进程(0x00000000),则函数失败,最后一个错误代码为ERROR_INVALID_PARAMETER。如果指定的进程是空闲进程或CSRSS之一进程,此函数失败,最后一个错误代码为ERROR_ACCESS_DENIED,因为它们的访问限制阻止用户级代码。

以下是我的系统上以非管理员身份运行的此代码输出的快照:

Process: [System Process] (0)
    hProcess = 00000000 (00000057) 
Process: System (4)
    hProcess = 00000000 (00000005)
Process: smss.exe (324)
    hProcess = 00000000 (00000005)
Process: csrss.exe (492)
    hProcess = 00000000 (00000005)
Process: wininit.exe (568)
    hProcess = 00000000 (00000005) 

请注意,当尝试打开[System Process](PID为0)时,错误正确地说是"无效参数"。当尝试打开System(PID为4)时,错误为5,转换为ERROR_ACCESS_DENIED。这就是我所期望的,因为我请求完全访问,而我不是以管理员身份运行。所以我试着以管理员的身份运行这个。然而,结果不会改变。嗯…可能是什么问题?

好吧,可能是你向那些即使你是管理员也不允许你请求那么多访问权限的进程请求PROCESS_ALL_ACCESS。仅仅因为你是ancyBank的所有者,并不意味着你可以走进分行,要求经理打开别人的保险箱。。。那么,不如您尝试请求LESS访问权限。改为PROCESS_QUERY_INFORMATION怎么样?

现在,证据(当你转发它时)表明,你对CreatToolHelp32Snapshot的呼叫失败了,循环从未进入,或者你以非管理员身份运行,并询问你无法访问的进程的信息。但我不相信你在准确地转发正在发生的事情,而你没有帮助我们帮助你。

操作系统将不允许您打开系统进程。这也将是非常无用的,因为这不是一个常见的过程与模块等

dwProcessId [in]
The identifier of the local process to be opened.

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.

此外,您还需要更高的权限才能打开另一个进程。您可以通过以管理员身份执行程序、要求UAC清单中的管理员或禁用UAC来测试此类应用程序。

To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege. For more information, see Changing Privileges in a Token.

在我禁用UAC的系统上,当我只将进程名称更改为可以打开的名称时,程序运行良好。

真正的问题是女士们和先生们:GetProcessId(HANDLE进程)来自windows.h,结果仍然返回0。我已将该功能替换为:

编辑:还有第二种方法可以解决这个问题,使用AdjustTokenPrivileges,因为我们可以使用PROCESS_ALL_ACCESS,所以原始的GetProcessId将在不使用下面简单创建远程线程的函数的情况下工作。

DWORD WINAPI GetProcessIDbyProcessHandle(HANDLE hProcess)
{
    if (hProcess == NULL)    return 0xffffffff;
    PTHREAD_START_ROUTINE lpStartAddress = (PTHREAD_START_ROUTINE)
        GetProcAddress(GetModuleHandle(TEXT("Kernel32")), "GetCurrentProcessId");
    if (lpStartAddress == NULL) return 0xffffffff;
    // We do not know, whether process handle already has required access rights;
    // thus we have to duplicate it
    HANDLE hProcessAccAdj;
    BOOL bRes = DuplicateHandle(GetCurrentProcess(), 
                                hProcess, GetCurrentProcess(), &hProcessAccAdj, 
                                PROCESS_QUERY_INFORMATION|PROCESS_CREATE_THREAD|
                                PROCESS_VM_OPERATION|PROCESS_VM_WRITE, 
                                FALSE, 0);
    if (!bRes || hProcessAccAdj == NULL)
    {
        UINT unError = GetLastError();
        return 0xffffffff;
    }
    // Create a remote thread; as its starting address 
    // we specify GetCurrentProcessId() address,
    // which is the same for all processes. Note that GetCurrentProcessId() has no input
    // parameters, and we don't care about our thread stack cleanup,
    // as it will be destroyed right after this call
    DWORD dwThreadID;
    HANDLE hRemoteThread = CreateRemoteThread(hProcessAccAdj, NULL, 
        0, lpStartAddress, 0, 0, &dwThreadID);
    CloseHandle(hProcessAccAdj);
    if (hRemoteThread == NULL) return 0xffffffff;
    // Wait until process ID is obtained
    // (replace INFINITE value below to a smaller value to avoid deadlocks);
    // then get the thread exit code, which is a value returned by GetCurrentProcessId()
    // in the context of the remote process
    WaitForSingleObject(hRemoteThread, INFINITE);
    DWORD dwExitCode;
    if (GetExitCodeThread(hRemoteThread, &dwExitCode) == 0)    dwExitCode = 0xffffffff;
    CloseHandle(hRemoteThread);
    return dwExitCode;
}