Getting a handle to the process's main thread

前端 未结 5 2216
暖寄归人
暖寄归人 2020-12-10 13:06

I have created an additional thread in some small testing app and want to suspend the main thread from this additional thread. The additional thread is created via Cre

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 13:27

    Get the thread id with this function:

    /* CAUTION: ONLY x86 TESTED
     * get the thread id of the main thread of a target process
     *
     * params:
     *     DWORD dwPid  process id of the target process
     *
     * return:
     *     Success      thread id
     *     Error        NULL
     */
    DWORD GetMainThreadId(DWORD dwPid)
    {
        LPVOID lpTid;
    
        _asm
        {
            mov eax, fs:[18h]
            add eax, 36
            mov [lpTid], eax
        }
    
        HANDLE hProcess = OpenProcess(PROCESS_VM_READ, FALSE, dwPid);
        if(hProcess == NULL)
            return NULL;
    
        DWORD dwTid;
        if(ReadProcessMemory(hProcess, lpTid, &dwTid, sizeof(dwTid), NULL) == FALSE)
        {
            CloseHandle(hProcess);
            return NULL;
        }
    
        CloseHandle(hProcess);
    
        return dwTid;
    }
    

    Simple open the thread to get the handle:

    /*
     * get a handle to the main thread of a target process
     * if successfull, the returned handle must be closed with CloseHandle()
     *
     * params:
     *     DWORD dwPid              process id of the target process
     *     DWORD dwDesiredAccess    desired access rights to the thread
     *
     * return:
     *     Success      thread handle with desired access rights
     *     Error        NULL
     */
    HANDLE GetMainThreadHandle(DWORD dwPid, DWORD dwDesiredAccess)
    {
        DWORD dwTid = GetMainThreadId(dwPid);
        if(dwTid == FALSE)
            return NULL;
    
        return OpenThread(dwDesiredAccess, FALSE, dwTid);
    }
    

提交回复
热议问题