From 7361b79da6f611478428ebac022ad41a22414c85 Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Sun, 5 Feb 2023 00:44:21 +0100 Subject: Added number_of_threads() --- process.cpp | 43 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 9 deletions(-) (limited to 'process.cpp') diff --git a/process.cpp b/process.cpp index 67cf1ce..c504330 100644 --- a/process.cpp +++ b/process.cpp @@ -16,23 +16,48 @@ namespace fs = std::filesystem; bool Reichwein::Process::is_running(pid_t pid) { - fs::path pid_file{"/proc/" + std::to_string(pid) + "/stat"}; - if (!fs::exists(pid_file)) - return false; + // 3rd position is status for pid + fs::path pid_file{"/proc/" + std::to_string(pid) + "/stat"}; + if (!fs::exists(pid_file)) + return false; - std::string s{Reichwein::File::getFile(pid_file)}; + std::string s{Reichwein::File::getFile(pid_file)}; - auto pos0{s.find(' ', 0)}; + auto pos0{s.find(' ', 0)}; + pos0 = s.find(' ', pos0 + 1); + pos0++; + + auto pos1{s.find(' ', pos0 + 1)}; + + std::string state{s.substr(pos0, pos1 - pos0)}; + + return state == "R" || state == "S"; +} + +int Reichwein::Process::number_of_threads(pid_t pid) +{ + // 20th position is the number of threads for pid + fs::path pid_file{"/proc/" + std::to_string(pid) + "/stat"}; + if (!fs::exists(pid_file)) + return false; + + std::string s{Reichwein::File::getFile(pid_file)}; + + size_t pos0{}; + for (int i = 0; i < 19; i++) { pos0 = s.find(' ', pos0 + 1); - pos0++; + if (pos0 == std::string::npos) + throw std::runtime_error("Bad format in /proc/" + std::to_string(pid) + "/stat"); + } - auto pos1{s.find(' ', pos0 + 1)}; + size_t pos1{s.find(' ', pos0 + 1)}; - std::string state{s.substr(pos0, pos1 - pos0)}; + std::string number_of_threads_s{s.substr(pos0, pos1 - pos0)}; - return state == "R" || state == "S"; + return std::stoi(number_of_threads_s); } + // tcp: tcp or tcp6 bool Reichwein::Process::tcp_is_pid_listening_on(const std::string& tcp, pid_t pid, int port) { -- cgit v1.2.3