process_iterator.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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_iterator.h"
  5. #include "build/build_config.h"
  6. namespace base {
  7. #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  8. ProcessEntry::ProcessEntry() : pid_(0), ppid_(0), gid_(0) {}
  9. ProcessEntry::ProcessEntry(const ProcessEntry& other) = default;
  10. ProcessEntry::~ProcessEntry() = default;
  11. #endif
  12. const ProcessEntry* ProcessIterator::NextProcessEntry() {
  13. bool result = false;
  14. do {
  15. result = CheckForNextProcess();
  16. } while (result && !IncludeEntry());
  17. if (result)
  18. return &entry_;
  19. return nullptr;
  20. }
  21. ProcessIterator::ProcessEntries ProcessIterator::Snapshot() {
  22. ProcessEntries found;
  23. while (const ProcessEntry* process_entry = NextProcessEntry()) {
  24. found.push_back(*process_entry);
  25. }
  26. return found;
  27. }
  28. bool ProcessIterator::IncludeEntry() {
  29. return !filter_ || filter_->Includes(entry_);
  30. }
  31. NamedProcessIterator::NamedProcessIterator(
  32. const FilePath::StringType& executable_name,
  33. const ProcessFilter* filter) : ProcessIterator(filter),
  34. executable_name_(executable_name) {
  35. #if BUILDFLAG(IS_ANDROID)
  36. // On Android, the process name contains only the last 15 characters, which
  37. // is in file /proc/<pid>/stat, the string between open parenthesis and close
  38. // parenthesis. Please See ProcessIterator::CheckForNextProcess for details.
  39. // Now if the length of input process name is greater than 15, only save the
  40. // last 15 characters.
  41. if (executable_name_.size() > 15) {
  42. executable_name_ = FilePath::StringType(executable_name_,
  43. executable_name_.size() - 15, 15);
  44. }
  45. #endif
  46. }
  47. NamedProcessIterator::~NamedProcessIterator() = default;
  48. int GetProcessCount(const FilePath::StringType& executable_name,
  49. const ProcessFilter* filter) {
  50. int count = 0;
  51. NamedProcessIterator iter(executable_name, filter);
  52. while (iter.NextProcessEntry())
  53. ++count;
  54. return count;
  55. }
  56. } // namespace base