Luna/apps/ps.cpp
apio 3db0c4fed2
All checks were successful
continuous-integration/drone/push Build is passing
apps: Add ps
2023-05-18 21:59:38 +02:00

45 lines
1.0 KiB
C++

#include <errno.h>
#include <os/ArgumentParser.h>
#include <os/File.h>
#include <pwd.h>
#include <sys/pstat.h>
#include <time.h>
Result<int> luna_main(int argc, char** argv)
{
os::ArgumentParser parser;
parser.add_description("Show a list of processes on the system.");
parser.add_system_program_info("ps"_sv);
parser.parse(argc, argv);
os::println("UID PID PPID TIME CMD");
pid_t last = pstat(-1, nullptr);
for (pid_t pid = 1; pid <= last; pid++)
{
static process ps;
if (pstat(pid, &ps) < 0)
{
if (errno == ESRCH) continue;
return err(errno);
}
struct tm tm;
gmtime_r(&ps.ps_time.tv_sec, &tm);
char timebuf[256];
strftime(timebuf, sizeof(timebuf), "%H:%M:%S", &tm);
const char* user = "???";
passwd* pw = getpwuid(ps.ps_uid);
if (pw) user = pw->pw_name;
os::println("%-8s %6d %6d %10s %s", user, ps.ps_pid, ps.ps_ppid, timebuf, ps.ps_name);
}
endpwent();
return 0;
}