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
5 #include "base/process/process_iterator.h"
6 #include "build/build_config.h"
7
8 namespace base {
9
10 #if defined(OS_POSIX) || defined(OS_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)38 NamedProcessIterator::NamedProcessIterator(
39 const FilePath::StringType& executable_name,
40 const ProcessFilter* filter) : ProcessIterator(filter),
41 executable_name_(executable_name) {
42 #if defined(OS_ANDROID)
43 // On Android, the process name contains only the last 15 characters, which
44 // is in file /proc/<pid>/stat, the string between open parenthesis and close
45 // parenthesis. Please See ProcessIterator::CheckForNextProcess for details.
46 // Now if the length of input process name is greater than 15, only save the
47 // last 15 characters.
48 if (executable_name_.size() > 15) {
49 executable_name_ = FilePath::StringType(executable_name_,
50 executable_name_.size() - 15, 15);
51 }
52 #endif
53 }
54
55 NamedProcessIterator::~NamedProcessIterator() = default;
56
GetProcessCount(const FilePath::StringType & executable_name,const ProcessFilter * filter)57 int GetProcessCount(const FilePath::StringType& executable_name,
58 const ProcessFilter* filter) {
59 int count = 0;
60 NamedProcessIterator iter(executable_name, filter);
61 while (iter.NextProcessEntry())
62 ++count;
63 return count;
64 }
65
66 } // namespace base
67