Trying to parse the output of a user-facing command usually becomes the most fragile part of your program, by a large margin. (Especially something as complex as pstree output.) The output is meant for humans and is not suitable for computer consumption. It can change between program versions, or depending on system locale (date, language, character set), or depending on the user's local customizations. Do not parse pstree.
On Linux, the main method to enumerate processes – the source of this information – is by listing subdirectories of /proc
/proc with numeric-only names. Each such directory represents a process and its name is the PID. Its parent can be determined by reading /proc/<pid>/status
and looking for the PPid:
attribute (alongside Pid:
itself).
To do this more conveniently, you can use one of the APIs provided by procps-nglibprocps: new API – procps_proctab_read()
, or old API – readproc()
, readproctab3()
.
To manage multiple instances of a service, use a service manager. Most Linux systems include one (called systemd). It automatically keeps track of which processes belong to which service, so that commands like systemctl restart smu@foo
(as well as the corresponding C APIs) always choose the right PIDs.