process_handle_win.cc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright (c) 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/process/process_handle.h"
  5. #include <windows.h>
  6. #include <tlhelp32.h>
  7. #include <ostream>
  8. #include "base/win/scoped_handle.h"
  9. #include "base/win/windows_version.h"
  10. namespace base {
  11. ProcessId GetCurrentProcId() {
  12. return ::GetCurrentProcessId();
  13. }
  14. ProcessHandle GetCurrentProcessHandle() {
  15. return ::GetCurrentProcess();
  16. }
  17. ProcessId GetProcId(ProcessHandle process) {
  18. if (process == base::kNullProcessHandle)
  19. return 0;
  20. // This returns 0 if we have insufficient rights to query the process handle.
  21. // Invalid handles or non-process handles will cause a hard failure.
  22. ProcessId result = GetProcessId(process);
  23. CHECK(result != 0 || GetLastError() != ERROR_INVALID_HANDLE)
  24. << "process handle = " << process;
  25. return result;
  26. }
  27. ProcessId GetParentProcessId(ProcessHandle process) {
  28. ProcessId child_pid = GetProcId(process);
  29. PROCESSENTRY32 process_entry;
  30. process_entry.dwSize = sizeof(PROCESSENTRY32);
  31. win::ScopedHandle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
  32. if (snapshot.is_valid() && Process32First(snapshot.get(), &process_entry)) {
  33. do {
  34. if (process_entry.th32ProcessID == child_pid)
  35. return process_entry.th32ParentProcessID;
  36. } while (Process32Next(snapshot.get(), &process_entry));
  37. }
  38. // TODO(zijiehe): To match other platforms, -1 (UINT32_MAX) should be returned
  39. // if |child_id| cannot be found in the |snapshot|.
  40. return 0u;
  41. }
  42. } // namespace base