xref: /aosp_15_r20/external/cronet/base/process/process_iterator.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/process/process_iterator.h"
6 #include "build/build_config.h"
7 
8 namespace base {
9 
10 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
ProcessEntry()11 ProcessEntry::ProcessEntry() : pid_(0), ppid_(0), gid_(0) {}
12 ProcessEntry::ProcessEntry(const ProcessEntry& other) = default;
13 ProcessEntry::~ProcessEntry() = default;
14 #endif
15 
NextProcessEntry()16 const ProcessEntry* ProcessIterator::NextProcessEntry() {
17   bool result = false;
18   do {
19     result = CheckForNextProcess();
20   } while (result && !IncludeEntry());
21   if (result)
22     return &entry_;
23   return nullptr;
24 }
25 
Snapshot()26 ProcessIterator::ProcessEntries ProcessIterator::Snapshot() {
27   ProcessEntries found;
28   while (const ProcessEntry* process_entry = NextProcessEntry()) {
29     found.push_back(*process_entry);
30   }
31   return found;
32 }
33 
IncludeEntry()34 bool ProcessIterator::IncludeEntry() {
35   return !filter_ || filter_->Includes(entry_);
36 }
37 
NamedProcessIterator(const FilePath::StringType & executable_name,const ProcessFilter * filter,bool use_prefix_match)38 NamedProcessIterator::NamedProcessIterator(
39     const FilePath::StringType& executable_name,
40     const ProcessFilter* filter,
41     bool use_prefix_match)
42     : ProcessIterator(filter),
43       executable_name_(executable_name),
44       use_prefix_match_(use_prefix_match) {
45 #if BUILDFLAG(IS_ANDROID)
46   // On Android, the process name contains only the last 15 characters, which
47   // is in file /proc/<pid>/stat, the string between open parenthesis and close
48   // parenthesis. Please See ProcessIterator::CheckForNextProcess for details.
49   // Now if the length of input process name is greater than 15, only save the
50   // last 15 characters.
51   if (executable_name_.size() > 15) {
52     executable_name_ = FilePath::StringType(executable_name_,
53                                             executable_name_.size() - 15, 15);
54   }
55 #endif
56 }
57 
58 NamedProcessIterator::~NamedProcessIterator() = default;
59 
GetProcessCount(const FilePath::StringType & executable_name,const ProcessFilter * filter)60 int GetProcessCount(const FilePath::StringType& executable_name,
61                     const ProcessFilter* filter) {
62   int count = 0;
63   NamedProcessIterator iter(executable_name, filter);
64   while (iter.NextProcessEntry())
65     ++count;
66   return count;
67 }
68 
69 }  // namespace base
70