2022-10-06 22:07:48 +08:00
|
|
|
#include "processes.h"
|
|
|
|
|
|
2026-01-06 09:48:38 +08:00
|
|
|
#include "common/io.h"
|
2026-08-28 15:21:52 +08:00
|
|
|
#include "common/memrchr.h"
|
2026-05-28 15:58:08 +08:00
|
|
|
#include "common/strutil.h"
|
2022-12-28 17:18:08 +08:00
|
|
|
|
2026-08-28 15:21:52 +08:00
|
|
|
const char* ffDetectProcesses(FFProcessesResult* result) {
|
2023-10-11 21:09:43 +08:00
|
|
|
FF_AUTO_CLOSE_DIR DIR* dir = opendir("/proc");
|
2026-07-10 18:08:04 +08:00
|
|
|
if (dir == nullptr) {
|
2023-10-11 21:09:43 +08:00
|
|
|
return "opendir(\"/proc\") failed";
|
2026-03-29 09:28:49 +08:00
|
|
|
}
|
2023-10-11 21:09:43 +08:00
|
|
|
|
2026-08-28 15:21:52 +08:00
|
|
|
uint32_t processes = 0;
|
|
|
|
|
uint32_t threads = 0;
|
|
|
|
|
|
|
|
|
|
int procfd = dirfd(dir);
|
2023-10-11 21:09:43 +08:00
|
|
|
|
|
|
|
|
struct dirent* entry;
|
2026-07-10 18:08:04 +08:00
|
|
|
while ((entry = readdir(dir)) != nullptr) {
|
2026-08-28 15:21:52 +08:00
|
|
|
if ((entry->d_type == DT_DIR || entry->d_type == DT_UNKNOWN) && ffCharIsDigit(entry->d_name[0])) {
|
|
|
|
|
++processes;
|
|
|
|
|
|
|
|
|
|
char statPath[32];
|
|
|
|
|
strcpy(ffStrCopy(statPath, entry->d_name, sizeof(statPath)), "/stat");
|
|
|
|
|
|
|
|
|
|
char statBuffer[256];
|
|
|
|
|
ssize_t statLength = ffReadFileDataRelative(procfd, statPath, sizeof(statBuffer) - 1, statBuffer);
|
|
|
|
|
if (statLength < 0) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
statBuffer[statLength] = '\0';
|
|
|
|
|
|
|
|
|
|
const char* cursor = (const char*) memrchr(statBuffer, ')', (size_t) statLength);
|
|
|
|
|
if (!cursor) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
++cursor;
|
|
|
|
|
|
|
|
|
|
for (uint32_t field = 2 /*comm*/; field < 20 /*num_threads*/; ++field) {
|
|
|
|
|
while (*cursor != ' ' && __builtin_expect(*cursor != '\0', true)) {
|
|
|
|
|
++cursor;
|
|
|
|
|
}
|
|
|
|
|
++cursor;
|
|
|
|
|
if (__builtin_expect(*cursor == '\0', false)) {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (__builtin_expect(*cursor == '\0', false)) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
threads += (uint32_t) strtoul(cursor, nullptr, 10);
|
|
|
|
|
}
|
2023-10-11 21:09:43 +08:00
|
|
|
}
|
|
|
|
|
|
2026-08-28 15:21:52 +08:00
|
|
|
result->processes = processes;
|
|
|
|
|
result->threads = threads;
|
2023-04-15 10:22:46 +08:00
|
|
|
|
2026-07-10 18:08:04 +08:00
|
|
|
return nullptr;
|
2022-10-06 22:07:48 +08:00
|
|
|
}
|