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