master ohmu/fastfetch-openbsd / src / detection / processes / processes_nbsd.c
ohmu  ·  2026-10-15
 1#include "processes.h"
 2#include "common/debug.h"
 3#include "common/mallocHelper.h"
 4
 5#include <errno.h>
 6#include <string.h>
 7#include <sys/sysctl.h>
 8
 9const char* ffDetectProcesses(const FFProcessesOptions* options, FFProcessesResult* result) {
10    int request[] = { CTL_KERN, KERN_PROC2, KERN_PROC_ALL, -1, sizeof(struct kinfo_proc2), INT_MAX };
11    size_t length = 0;
12
13    if (sysctl(request, ARRAY_SIZE(request), nullptr, &length, nullptr, 0) != 0) {
14        FF_DEBUG("sysctl({CTL_KERN, KERN_PROC2, KERN_PROC_ALL, nullptr}) failed: %s", strerror(errno));
15        return "sysctl({CTL_KERN, KERN_PROC2, KERN_PROC_ALL, nullptr}) failed";
16    }
17
18    FF_AUTO_FREE struct kinfo_proc2* procs = malloc(length);
19    if (sysctl(request, ARRAY_SIZE(request), procs, &length, nullptr, 0) != 0) {
20        FF_DEBUG("sysctl({CTL_KERN, KERN_PROC2, KERN_PROC_ALL, procs}) failed: %s", strerror(errno));
21        return "sysctl({CTL_KERN, KERN_PROC2, KERN_PROC_ALL, procs}) failed";
22    }
23
24    uint32_t procCount = (uint32_t) (length / sizeof(struct kinfo_proc2));
25
26    for (uint32_t i = 0; i < procCount; ++i) {
27        const struct kinfo_proc2* proc = &procs[i];
28        if (!options->countKprocs && (proc->p_flag & P_SYSTEM)) {
29            continue;
30        }
31        ++result->processes;
32
33        int lwpRequest[] = { CTL_KERN, KERN_LWP, procs[i].p_pid, sizeof(struct kinfo_lwp), 0 };
34        size_t lwpLength = 0;
35
36        if (sysctl(lwpRequest, ARRAY_SIZE(lwpRequest), nullptr, &lwpLength, nullptr, 0) == 0) {
37            result->threads += (uint32_t) (lwpLength / sizeof(struct kinfo_lwp));
38        }
39    }
40
41    return nullptr;
42}