Recently, I needed to fetch the parent PID of arbitrary (Linux) processes from userspace (in C). For some reason, no standards define this function (
The primary and only supported version to accomplish this is by reading the first process’ status file exported by the kernel in
/proc/<pid>/stat (which is only available in Linux). This file contains the parent’s PID as the fourth parameter, space separated, preceded by, among others, the executable name (in parentheses, for some reason).
Documentation (as in,
man proc) tells us to parse this file using the
scanf family, even providing the proper escape codes - which are subtly wrong.
When including a space character in the executable name, the
%s escape will not read all of the executable name, breaking all subsequent reads. This problem affects some tools using this recommended method of parsing. Using the parentheses as separators does not work for the same reason, as does ‘read until we see numbers again’.
The only reasonable way to do this with the current layout of the stats file would be to read all of the file and scan it from the end, since there are only numeric parameters after the executable name / current state fields, or search for the last closing parenthesis in the file.
The proper fix (aside from introducing the above function) however should probably be to either sanitize the executable name before exposing it to
/proc/<pid>/stat, or move it to be the last parameter in the file.
This problem could potentially be used to feed process-controlled data to all tools relying on reading
/proc/<pid>/stat using the recommended method (which includes several monitoring tools).