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 <dirent.h>
16 #include <errno.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <sys/types.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
30 template <typename Func>
ScanPidsInDir(const std::string & name,Func f)31 static bool ScanPidsInDir(const 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
Scan(std::map<pid_t,std::vector<pid_t>> & tgid_map)48 bool 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
ScanPid(pid_t tgid,std::vector<pid_t> & pid_list)59 bool 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) { pid_list.push_back(pid); });
63 }
64