CProcessStatisticsReader.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <AK/JsonArray.h>
  2. #include <AK/JsonObject.h>
  3. #include <AK/JsonValue.h>
  4. #include <LibCore/CFile.h>
  5. #include <LibCore/CProcessStatisticsReader.h>
  6. #include <pwd.h>
  7. #include <stdio.h>
  8. CProcessStatisticsReader::CProcessStatisticsReader()
  9. {
  10. setpwent();
  11. while (auto* passwd = getpwent())
  12. m_usernames.set(passwd->pw_uid, passwd->pw_name);
  13. endpwent();
  14. }
  15. HashMap<pid_t, CProcessStatistics> CProcessStatisticsReader::get_map()
  16. {
  17. HashMap<pid_t, CProcessStatistics> res;
  18. update_map(res);
  19. return res;
  20. }
  21. void CProcessStatisticsReader::update_map(HashMap<pid_t, CProcessStatistics>& map)
  22. {
  23. CFile file("/proc/all");
  24. if (!file.open(CIODevice::ReadOnly)) {
  25. fprintf(stderr, "CProcessHelper : failed to open /proc/all: %s\n", file.error_string());
  26. return;
  27. }
  28. auto file_contents = file.read_all();
  29. auto json = JsonValue::from_string({ file_contents.data(), file_contents.size() });
  30. json.as_array().for_each([&](auto& value) {
  31. const JsonObject& process_object = value.as_object();
  32. CProcessStatistics process;
  33. process.pid = process_object.get("pid").to_dword();
  34. process.nsched = process_object.get("times_scheduled").to_dword();
  35. process.uid = process_object.get("uid").to_dword();
  36. process.username = get_username_from_uid(process.uid);
  37. process.priority = process_object.get("priority").to_string();
  38. process.syscalls = process_object.get("syscall_count").to_dword();
  39. process.state = process_object.get("state").to_string();
  40. process.name = process_object.get("name").to_string();
  41. process.virtual_size = process_object.get("amount_virtual").to_dword();
  42. process.physical_size = process_object.get("amount_resident").to_dword();
  43. map.set(process.pid, process);
  44. });
  45. }
  46. String CProcessStatisticsReader::get_username_from_uid(const uid_t uid)
  47. {
  48. auto it = m_usernames.find(uid);
  49. if (it != m_usernames.end())
  50. return (*it).value;
  51. else
  52. return String::format("%u", uid);
  53. }