I am tasked to implement a simple version of pstree
(linux command), while I am confused about the content between what pstree
shows and what I find under /proc/[pid]
directory.
After I type pstree
, it shows the root of the whole process tree is systemd
, just like this:
systemd─┬─ECAgent───3*[{ECAgent}]
├─EasyMonitor
├─ModemManager───2*[{ModemManager}]
├─NetworkManager─┬─dhclient
While after I try to read all /proc/[pid]/stat
files, I got the following result (do a little formatting):
pid comm state ppid
1 systemd S 0
2 kthreadd S 0
3 rcu_gp I 2
4 rcu_par_gp I 2
It seems that there is another process kthreadd
that is paralleled with systemd
. This is different from what shows in pstree
command.
After reading some manuals and web materials, I know that pstree
displays all runnnig processes and kthreadd
is the root thread of all related threads. But I am still confused that kthreadd
doesn't count as a running process by pstree
command. So it's like kthreadd
is not a process even it owns one pid (which is 2)? Should I include kthreadd
as a running process in my version of pstree
?
kthreadd is not a process started by systemd. Kthreadd is a worker thread in kernel address space started by the kernel.
pstree is more to do with the user space processes that shows the parent and child hierarchy.
In my opinion you should not include kthreadd in your implementation. One of the way to find the kernel threads is /proc/$pid/cmdline is empty for kernel threads.