CProcessStatisticsReader.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. HashMap<uid_t, String> CProcessStatisticsReader::s_usernames;
  9. HashMap<pid_t, CProcessStatistics> CProcessStatisticsReader::get_all()
  10. {
  11. CFile file("/proc/all");
  12. if (!file.open(CIODevice::ReadOnly)) {
  13. fprintf(stderr, "CProcessStatisticsReader: Failed to open /proc/all: %s\n", file.error_string());
  14. return {};
  15. }
  16. HashMap<pid_t, CProcessStatistics> map;
  17. auto file_contents = file.read_all();
  18. auto json = JsonValue::from_string({ file_contents.data(), file_contents.size() });
  19. json.as_array().for_each([&](auto& value) {
  20. const JsonObject& process_object = value.as_object();
  21. CProcessStatistics process;
  22. process.pid = process_object.get("pid").to_u32();
  23. process.nsched = process_object.get("times_scheduled").to_u32();
  24. process.uid = process_object.get("uid").to_u32();
  25. process.username = username_from_uid(process.uid);
  26. process.priority = process_object.get("priority").to_string();
  27. process.syscalls = process_object.get("syscall_count").to_u32();
  28. process.state = process_object.get("state").to_string();
  29. process.name = process_object.get("name").to_string();
  30. process.virtual_size = process_object.get("amount_virtual").to_u32();
  31. process.physical_size = process_object.get("amount_resident").to_u32();
  32. map.set(process.pid, process);
  33. });
  34. return map;
  35. }
  36. String CProcessStatisticsReader::username_from_uid(uid_t uid)
  37. {
  38. if (s_usernames.is_empty()) {
  39. setpwent();
  40. while (auto* passwd = getpwent())
  41. s_usernames.set(passwd->pw_uid, passwd->pw_name);
  42. endpwent();
  43. }
  44. auto it = s_usernames.find(uid);
  45. if (it != s_usernames.end())
  46. return (*it).value;
  47. return String::number(uid);
  48. }