Way to unambiguously parse /proc/<pid>/stat (given arbitrary contents of name field)

The format of /proc/<pid>/stat is documented in the proc(5) manpage.

There cannot be another (...) field, nor could be added in the future, because that would make the format ambiguous. That's quite easy to see in.

The kernel code which formats the /proc/<pid>/stat file is in fs/proc/array.c.

The OP won't tell which language they're using. In perl, something like this could be used:

my @s = readfile("/proc/$pid/stat") =~ /(?<=\().*(?=\))|[^\s()]+/gs;

Notice the s: the "command" field can also contain newlines.

Tags:

Proc