Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the main thread ID of a process (known by its ID)?

Can you help me to find the main (only) thread ID of a given by ID process, please ?

Task context: A running process has (at the moment) no windows but a(some) thread(s).

Wanted: Posting of WM_QUIT at the main thread only.

Not-wanted: Using of TerminateProcess or posting WM_QUIT at the non-primary threads.

like image 962
Smehrt Tonni Avatar asked Mar 24 '13 09:03

Smehrt Tonni


2 Answers

A much simpler and surer way to get the thread id of the main thread is to let the main thread records its own thread id using ::GetCurrentThreadId() into a shared global variable, perhaps in your WinMain or somewhere at the very beginning of your 'main thread':

MainThreadId_G = ::GetCurrentThreadId();

then in your other threads, you can call: ::PostThreadMessage(MainThreadId_G, WM_QUIT, returncode, 0);

like image 145
Nibikibaba Avatar answered Oct 22 '22 08:10

Nibikibaba


#ifndef MAKEULONGLONG
#define MAKEULONGLONG(ldw, hdw) ((ULONGLONG(hdw) << 32) | ((ldw) & 0xFFFFFFFF))
#endif

#ifndef MAXULONGLONG
#define MAXULONGLONG ((ULONGLONG)~((ULONGLONG)0))
#endif

bool CloseProcessMainThread(DWORD dwProcID)
{
  DWORD dwMainThreadID = 0;
  ULONGLONG ullMinCreateTime = MAXULONGLONG;

  HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
  if (hThreadSnap != INVALID_HANDLE_VALUE) {
    THREADENTRY32 th32;
    th32.dwSize = sizeof(THREADENTRY32);
    BOOL bOK = TRUE;
    for (bOK = Thread32First(hThreadSnap, &th32); bOK;
         bOK = Thread32Next(hThreadSnap, &th32)) {
      if (th32.th32OwnerProcessID == dwProcID) {
        HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION,
                                    TRUE, th32.th32ThreadID);
        if (hThread) {
          FILETIME afTimes[4] = {0};
          if (GetThreadTimes(hThread,
                             &afTimes[0], &afTimes[1], &afTimes[2], &afTimes[3])) {
            ULONGLONG ullTest = MAKEULONGLONG(afTimes[0].dwLowDateTime,
                                              afTimes[0].dwHighDateTime);
            if (ullTest && ullTest < ullMinCreateTime) {
              ullMinCreateTime = ullTest;
              dwMainThreadID = th32.th32ThreadID; // let it be main... :)
            }
          }
          CloseHandle(hThread);
        }
      }
    }
#ifndef UNDER_CE
    CloseHandle(hThreadSnap);
#else
    CloseToolhelp32Snapshot(hThreadSnap);
#endif
  }

  if (dwMainThreadID) {
    PostThreadMessage(dwMainThreadID, WM_QUIT, 0, 0); // close your eyes...
  }

  return (0 != dwMainThreadID);
}
like image 32
George Netu Avatar answered Oct 22 '22 08:10

George Netu