ohmu
·
2026-10-15
1#include "processes.h"
2
3#include "common/debug.h"
4#include "common/mallocHelper.h"
5
6#include <errno.h>
7#include <string.h>
8#include <sys/param.h>
9#include <sys/sysctl.h>
10
11const char* ffDetectProcesses(const FFProcessesOptions* options, FFProcessesResult* result) {
12 int request[] = { CTL_KERN, KERN_PROC, (options->countKprocs ? KERN_PROC_KTHREAD : KERN_PROC_ALL) | KERN_PROC_SHOW_THREADS, 0, (int) sizeof(struct kinfo_proc), 0 };
13 size_t length = 0;
14
15 if (sysctl(request, ARRAY_SIZE(request), nullptr, &length, nullptr, 0) != 0) {
16 FF_DEBUG("sysctl({CTL_KERN, KERN_PROC, KERN_PROC_ALL}, nullptr) failed: %s", strerror(errno));
17 return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_ALL}, nullptr) failed";
18 }
19
20 FF_AUTO_FREE struct kinfo_proc* procs = (struct kinfo_proc*) malloc(length);
21 request[5] = (int) (length / sizeof(struct kinfo_proc)); // count must be non-zero for data fetch
22 if (sysctl(request, ARRAY_SIZE(request), procs, &length, nullptr, 0) != 0) {
23 FF_DEBUG("sysctl({CTL_KERN, KERN_PROC, KERN_PROC_ALL}, procs) failed: %s", strerror(errno));
24 return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_ALL}, procs) failed";
25 }
26
27 int count = (int) (length / sizeof(struct kinfo_proc));
28 for (int i = 0; i < count; ++i) {
29 const struct kinfo_proc* proc = &procs[i];
30
31 ++result->threads;
32 if (proc->p_tid == -1) {
33 ++result->processes;
34 }
35 }
36
37 return nullptr;
38}