tasklist.cpp revision 66dd09e8e2407082ce93bf0784de641298131912
1// Copyright (C) 2015 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15#include <sys/types.h> 16#include <dirent.h> 17#include <errno.h> 18#include <stdlib.h> 19#include <string.h> 20 21#include <map> 22#include <memory> 23#include <string> 24#include <vector> 25 26#include <android-base/stringprintf.h> 27 28#include "tasklist.h" 29 30template<typename Func> 31static bool ScanPidsInDir(std::string name, Func f) { 32 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(name.c_str()), closedir); 33 if (!dir) { 34 return false; 35 } 36 37 dirent* entry; 38 while ((entry = readdir(dir.get())) != nullptr) { 39 if (isdigit(entry->d_name[0])) { 40 pid_t pid = atoi(entry->d_name); 41 f(pid); 42 } 43 } 44 45 return true; 46} 47 48bool TaskList::Scan(std::map<pid_t, std::vector<pid_t>>& tgid_map) { 49 tgid_map.clear(); 50 51 return ScanPidsInDir("/proc", [&tgid_map](pid_t tgid) { 52 std::vector<pid_t> pid_list; 53 if (ScanPid(tgid, pid_list)) { 54 tgid_map.insert({tgid, pid_list}); 55 } 56 }); 57} 58 59bool TaskList::ScanPid(pid_t tgid, std::vector<pid_t>& pid_list) { 60 std::string filename = android::base::StringPrintf("/proc/%d/task", tgid); 61 62 return ScanPidsInDir(filename, [&pid_list](pid_t pid) { 63 pid_list.push_back(pid); 64 }); 65} 66