master ohmu/fastfetch-openbsd / src / detection / processes / processes_dbsd.c
ohmu  ·  2026-10-15
 1#include "processes.h"
 2#include "common/mallocHelper.h"
 3
 4#include <sys/sysctl.h>
 5#include <sys/types.h>
 6#include <sys/user.h>
 7#include <sys/proc.h>
 8
 9const char* ffDetectProcesses(const FFProcessesOptions* options, FFProcessesResult* result) {
10    int request[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL | (options->countKprocs ? KERN_PROC_FLAG_LWKT : 0) };
11    size_t length;
12    if (sysctl(request, ARRAY_SIZE(request), nullptr, &length, nullptr, 0) != 0) {
13        return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_ALL}) failed";
14    }
15
16    // The process table may change between the two sysctl calls; retry with a larger buffer.
17    length += length / 8 + sizeof(struct kinfo_proc);
18    FF_AUTO_FREE struct kinfo_proc* procs = malloc(length);
19    if (sysctl(request, ARRAY_SIZE(request), procs, &length, nullptr, 0) != 0) {
20        return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_ALL}) failed";
21    }
22
23    uint32_t count = (uint32_t) (length / sizeof(struct kinfo_proc));
24    for (uint32_t i = 0; i < count; ++i) {
25        const struct kinfo_proc* proc = &procs[i];
26
27        if (proc->kp_pid == -1) {
28            // Kernel thread, only returned when countKprocs is set via KERN_PROC_FLAG_LWKT
29            result->threads++;
30            continue;
31        }
32
33        result->processes++;
34        result->threads += (uint32_t) proc->kp_nthreads;
35    }
36
37    return nullptr;
38}