CX Framework
Cross-platform C utility framework
Loading...
Searching...
No Matches
linux_procfs.h
1#pragma once
2
3// Small shared readers for /proc, used by the Linux process and statistics backends. Nothing
4// here is cx API; it exists so the two backends parse the same files the same way.
5
6#include <cx/cx.h>
7
8#include <sys/types.h>
9
10// Read a small /proc file whole. These are generated on read and always tiny, so one read is
11// enough. Returns the byte count, or -1 if the file could not be read -- which for a per-process
12// file usually means the process exited while we were looking at it, and for /proc/<pid>/io
13// means it belongs to another user.
14ssize_t _linuxReadProcFile(const char* path, char* buf, size_t sz);
15
16// Read a /proc file whose length cannot be bounded in advance. /proc/stat in particular grows
17// with both the processor count and the number of interrupt sources, so the fields at the end of
18// it sit well past any fixed buffer on a large machine. Returns a NUL-terminated buffer to free
19// with xaFree(), or NULL if the file could not be read.
20char* _linuxReadProcFileAlloc(const char* path);
21
22// Read one numeric field from a /proc/<pid>/stat line, counting from the field after the
23// executable name: index 0 is the state, 1 the parent pid, 11 and 12 the user and system times,
24// 19 the start time, 20 the address space size and 21 the resident set (fields 3, 4, 14, 15,
25// 22, 23 and 24 of the line as documented in proc(5)).
26//
27// Field 2 is the executable name in parentheses, and it can itself contain both spaces and
28// parentheses -- a process named "ev(il) name" is legal. Scanning for the LAST ')' is the only
29// reliable way to find where the fixed-width fields begin; sscanf on the whole line gets this
30// wrong for any such process.
31bool _linuxParseStatField(const char* stat, int idx, int64* out);
32
33// Read one numeric value out of the "Name:<whitespace>value" lines that /proc/meminfo and
34// /proc/<pid>/{status,io} are made of. key must include the colon. The value is returned as
35// written, so a line ending in "kB" yields kilobytes, not bytes.
36bool _linuxProcFileField(const char* buf, const char* key, int64* out);