Yabin Cui | 323e945 | 2015-04-20 18:07:17 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2015 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 | #include "environment.h" |
| 18 | |
| 19 | #include <stdlib.h> |
| 20 | #include <vector> |
| 21 | |
| 22 | #include <base/logging.h> |
| 23 | |
| 24 | #include "utils.h" |
| 25 | |
| 26 | std::vector<int> GetOnlineCpus() { |
| 27 | std::vector<int> result; |
| 28 | FILE* fp = fopen("/sys/devices/system/cpu/online", "re"); |
| 29 | if (fp == nullptr) { |
| 30 | PLOG(ERROR) << "can't open online cpu information"; |
| 31 | return result; |
| 32 | } |
| 33 | |
| 34 | LineReader reader(fp); |
| 35 | char* line; |
| 36 | if ((line = reader.ReadLine()) != nullptr) { |
| 37 | result = GetOnlineCpusFromString(line); |
| 38 | } |
| 39 | CHECK(!result.empty()) << "can't get online cpu information"; |
| 40 | return result; |
| 41 | } |
| 42 | |
| 43 | std::vector<int> GetOnlineCpusFromString(const std::string& s) { |
| 44 | std::vector<int> result; |
| 45 | bool have_dash = false; |
| 46 | const char* p = s.c_str(); |
| 47 | char* endp; |
| 48 | long cpu; |
| 49 | // Parse line like: 0,1-3, 5, 7-8 |
| 50 | while ((cpu = strtol(p, &endp, 10)) != 0 || endp != p) { |
| 51 | if (have_dash && result.size() > 0) { |
| 52 | for (int t = result.back() + 1; t < cpu; ++t) { |
| 53 | result.push_back(t); |
| 54 | } |
| 55 | } |
| 56 | have_dash = false; |
| 57 | result.push_back(cpu); |
| 58 | p = endp; |
| 59 | while (!isdigit(*p) && *p != '\0') { |
| 60 | if (*p == '-') { |
| 61 | have_dash = true; |
| 62 | } |
| 63 | ++p; |
| 64 | } |
| 65 | } |
| 66 | return result; |
| 67 | } |