Userspace: Add meminfo command that parses /proc/{pid}/meminfo

This commit is contained in:
Bananymous 2023-09-30 21:20:53 +03:00
parent a511441f7e
commit 762b7a4276
3 changed files with 75 additions and 0 deletions

View File

@ -10,6 +10,7 @@ set(USERSPACE_PROJECTS
id id
init init
ls ls
meminfo
mmap-shared-test mmap-shared-test
poweroff poweroff
Shell Shell

View File

@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.26)
project(meminfo CXX)
set(SOURCES
main.cpp
)
add_executable(meminfo ${SOURCES})
target_compile_options(meminfo PUBLIC -O2 -g)
target_link_libraries(meminfo PUBLIC libc)
add_custom_target(meminfo-install
COMMAND sudo cp ${CMAKE_CURRENT_BINARY_DIR}/meminfo ${BANAN_BIN}/
DEPENDS meminfo
USES_TERMINAL
)

View File

@ -0,0 +1,57 @@
#include <ctype.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/banan-os.h>
bool is_only_digits(const char* str)
{
while (*str)
if (!isdigit(*str++))
return false;
return true;
}
int main()
{
DIR* proc = opendir("/proc");
if (proc == nullptr)
{
perror("opendir");
return 1;
}
char path_buffer[128] {};
while (dirent* proc_ent = readdir(proc))
{
if (proc_ent->d_type != DT_DIR)
continue;
if (!is_only_digits(proc_ent->d_name))
continue;
strcpy(path_buffer, proc_ent->d_name);
strcat(path_buffer, "/meminfo");
int fd = openat(dirfd(proc), path_buffer, O_RDONLY);
if (fd == -1)
{
perror("openat");
continue;
}
proc_meminfo_t meminfo;
if (read(fd, &meminfo, sizeof(meminfo)) == -1)
perror("read");
else
{
printf("process:\n");
printf(" pid: %s\n", proc_ent->d_name);
printf(" vmem: %zu pages (%zu bytes)\n", meminfo.virt_pages, meminfo.page_size * meminfo.virt_pages);
}
close(fd);
}
closedir(proc);
}