CProcessStatisticsReader.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. // kernel data first
  23. process.pid = process_object.get("pid").to_u32();
  24. process.times_scheduled = process_object.get("times_scheduled").to_u32();
  25. process.pgid = process_object.get("pgid").to_u32();
  26. process.pgp = process_object.get("pgp").to_u32();
  27. process.sid = process_object.get("sid").to_u32();
  28. process.uid = process_object.get("uid").to_u32();
  29. process.gid = process_object.get("gid").to_u32();
  30. process.state = process_object.get("state").to_string();
  31. process.ppid = process_object.get("ppid").to_u32();
  32. process.nfds = process_object.get("nfds").to_u32();
  33. process.name = process_object.get("name").to_string();
  34. process.tty = process_object.get("tty").to_string();
  35. process.amount_virtual = process_object.get("amount_virtual").to_u32();
  36. process.amount_resident = process_object.get("amount_resident").to_u32();
  37. process.amount_shared = process_object.get("amount_shared").to_u32();
  38. process.ticks = process_object.get("ticks").to_u32();
  39. process.priority = process_object.get("priority").to_string();
  40. process.syscall_count = process_object.get("syscall_count").to_u32();
  41. process.icon_id = process_object.get("icon_id").to_int();
  42. // and synthetic data last
  43. process.username = username_from_uid(process.uid);
  44. map.set(process.pid, process);
  45. });
  46. return map;
  47. }
  48. String CProcessStatisticsReader::username_from_uid(uid_t uid)
  49. {
  50. if (s_usernames.is_empty()) {
  51. setpwent();
  52. while (auto* passwd = getpwent())
  53. s_usernames.set(passwd->pw_uid, passwd->pw_name);
  54. endpwent();
  55. }
  56. auto it = s_usernames.find(uid);
  57. if (it != s_usernames.end())
  58. return (*it).value;
  59. return String::number(uid);
  60. }