CProcessStatisticsReader.cpp 2.5 KB

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