1 /* 2 * Copyright (C) 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <dirent.h> 20 #include <sys/types.h> 21 22 #include <iterator> 23 #include <memory> 24 #include <vector> 25 26 namespace android { 27 namespace base { 28 29 class AllPids { 30 class PidIterator { 31 public: PidIterator(DIR * dir)32 PidIterator(DIR* dir) : dir_(dir, closedir) { Increment(); } 33 PidIterator& operator++() { 34 Increment(); 35 return *this; 36 } 37 bool operator==(const PidIterator& other) const { return pid_ == other.pid_; } 38 bool operator!=(const PidIterator& other) const { return !(*this == other); } 39 long operator*() const { return pid_; } 40 // iterator traits 41 using difference_type = pid_t; 42 using value_type = pid_t; 43 using pointer = const pid_t*; 44 using reference = const pid_t&; 45 using iterator_category = std::input_iterator_tag; 46 47 private: 48 void Increment(); 49 50 pid_t pid_ = -1; 51 std::unique_ptr<DIR, decltype(&closedir)> dir_; 52 }; 53 54 public: begin()55 PidIterator begin() { return opendir("/proc"); } end()56 PidIterator end() { return nullptr; } 57 }; 58 59 } // namespace base 60 } // namespace android 61