Advertisement
Guest User

Untitled

a guest
Feb 20th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #ifdef _MSC_VER
  2. #define NOMINMAX
  3. #define WIN32_LEAN_AND_MEAN
  4. #include <windows.h>
  5. #include <tlhelp32.h>
  6. #else
  7. #include <pthread.h>
  8. #endif
  9.  
  10. int is_main_thread()
  11. {
  12. #ifdef _MSC_VER
  13. DWORD pid = GetCurrentProcessId();
  14. FILETIME now;
  15. SYSTEMTIME st;
  16. GetSystemTime(&st);
  17. if (!SystemTimeToFileTime(&st, &now)) {
  18. return -1;
  19. }
  20. FILETIME oldest = now;
  21. DWORD oldest_tid = 0;
  22.  
  23. std::shared_ptr<void> h(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0), CloseHandle);
  24. if (h.get() == INVALID_HANDLE_VALUE) {
  25. return -1;
  26. }
  27. THREADENTRY32 te;
  28. te.dwSize = sizeof(te);
  29. if (!Thread32First(h.get(), &te)) {
  30. return -1;
  31. }
  32. do {
  33. if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID)) {
  34. if (te.th32OwnerProcessID == pid) {
  35. std::shared_ptr<void> th(OpenThread(THREAD_QUERY_LIMITED_INFORMATION, FALSE, te.th32ThreadID), CloseHandle);
  36. if (th.get() == INVALID_HANDLE_VALUE) {
  37. return -1;
  38. }
  39. FILETIME creation, e, k, u;
  40. if (!GetThreadTimes(th.get(), &creation, &e, &k, &u)) {
  41. return -1;
  42. }
  43. if (oldest_tid == 0) {
  44. oldest = creation;
  45. oldest_tid = te.th32ThreadID;
  46. } else if (CompareFileTime(&oldest, &creation) >= 0) {
  47. oldest = creation;
  48. oldest_tid = te.th32ThreadID;
  49. }
  50. }
  51. }
  52. te.dwSize = sizeof(te);
  53. } while(Thread32Next(h.get(), &te));
  54.  
  55. if (oldest_tid == 0) {
  56. return -1;
  57. }
  58.  
  59. if (oldest_tid == GetCurrentThreadId()) {
  60. return 1;
  61. } else {
  62. return 0;
  63. }
  64. #else
  65. if (pthread_main_np() != 0) {
  66. return 1;
  67. } else {
  68. return 0;
  69. }
  70. #endif
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement