Linux — namespaces: PID namespace

Shlomi Boutnaru, Ph.D.
2 min readFeb 26, 2023

--

In the first part of the series we have talked generally about what are namespace and what we can do with them — in case you want to go over it you can use the following link https://medium.com/@boutnaru/linux-namespaces-part-1-dcee9c40fb68. Now we are going to deep dive into pid namespaces.

The goal of PID namespaces is to isolate the “Process ID number space”. Thus, different processes in distinct PID namespaces can have the same PID. When a new PID namespace is started the first process gets PID 1 (so we don’t have a new swapper — https://medium.com/@boutnaru/the-linux-process-journey-pid-0-swapper-7868d1131316). In order to use PID namespaces we have to ensure that our kernel was compiled with “CONFIG_PID_NS” enabled (https://man7.org/linux/man-pages/man7/pid_namespaces.7.html).

Moreover, PID namespace can also be nested , since kernel 3.7 the maximum nesting depth is 32. A process is visible to every other process in the same PID namespace or any direct ancestor PID namespace. The opposite way does not work, a process in a child PID namespace can’t see a process in a parent PID namespace (https://www.schutzwerk.com/en/blog/linux-container-namespaces03-pid-net/).

Also, “/proc” will show only processes which are visible in the PID namespace of the process that executed the “mount” operation for “/proc” (https://lwn.net/Articles/531419/). If we want to see the number of the last pid that was allocated in our PID namespace we can use “/proc/sys/kernel/ns_last_pid” (https://www.kernel.org/doc/html/latest/admin-guide/sysctl/kernel.html#ns-last-pid) — as you can see in the screenshot below.

Lastly, a nice fact to know is that when we pass a pid over a unix domain socket to a process which belongs to another PID namespace, it is resolved to the correct value in the receiving process’ PID namespace (https://man7.org/linux/man-pages/man7/pid_namespaces.7.html).

See you next time ;-) You can also follow me on twitter — @boutnaru (https://twitter.com/boutnaru).

--

--