TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Broken API: /proc/pid/stat

1 pointsby _cbdevover 7 years ago
Recently, I needed to fetch the parent PID of arbitrary (Linux) processes from userspace (in C). For some reason, no standards define this function (pid_t ppid(pid_t)).<p>The primary and only supported version to accomplish this is by reading the first process&#x27; status file exported by the kernel in &#x2F;proc&#x2F;&lt;pid&gt;&#x2F;stat (which is only available in Linux). This file contains the parent&#x27;s PID as the fourth parameter, space separated, preceded by, among others, the executable name (in parentheses, for some reason).<p>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.<p>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 &#x27;read until we see numbers again&#x27;.<p>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 &#x2F; current state fields.<p>The proper fix (aside from introducing the above function) however should probably be to either sanitize the executable name before exposing it to &#x2F;proc&#x2F;&lt;pid&gt;&#x2F;stat, or move it to be the last parameter in the file.<p>This problem could potentially be used to feed process-controlled data to all tools relying on reading &#x2F;proc&#x2F;&lt;pid&gt;&#x2F;stat using the recommended method, which includes several monitoring tools.

no comments

no comments