Linux namespaces

How PID namespaces isolate the process view in Linux, with examples using fork and clone.

Linux logo

The process identifier (PID) is a number the kernel uses to uniquely refer to processes running on a machine. PIDs are used to interact with processes, for example by sending signals or changing their priority with nice. Each process has a unique PID (no other active process can have the same one). However, the introduction of PID namespaces in Linux 2.6.24 changed this. Here is a Perl example:

# A process clones a child process and waits for it to finish.
use strict;
use Eixo::Zone;

my $child_pid = Eixo::Zone->init(
    init => sub {
        print "I am the child process and (in my namespace) my pid is " . &Eixo::Zone::getPid() . "\n";
        sleep(1);
        exit(0);
    }
);

print "I am the parent process and my child's pid is $child_pid \n";
waitpid($child_pid, 0);

Output:

I am the parent process and my child's pid is 26708
I am the child process and (in my namespace) my pid is 1

Unified cgroups and systemd hierarchy in the Linux kernel

What happened?

A) Traditional child process creation

Let’s start with a normal child process created with fork. The child is an exact copy of its parent and starts at the fork() call.

B) Creating a child process with clone

The Perl example uses clone. Among other things, this call lets us create new namespaces when creating a child process. We specify which private namespaces the child should have. If we tell it to create its own PID namespace, the child process lives in its own namespace and therefore has two PIDs: one in its parent’s space and one in its own.

To learn its PID, a process calls the kernel with getpid(). If the child asks the kernel for its PID:

print "I am the child process and (in my namespace) my pid is " . &Eixo::Zone::getPid() . "\n";

The kernel returns the PID the child has within its namespace (PID = 1). In other words, the kernel contextualises process calls according to their namespace.

The parent wants to wait for the child to finish, so it uses waitpid:

waitpid($child_pid, 0);

It waits until the child process exits. Which PID does it use? From its point of view (its namespace), the child’s PID is the one returned by the clone call, and that is the one it uses to wait.

Processes with PID = 1

The first process to enter a PID namespace receives PID 1 within it. This matters:

Next in the series

In part two, we look at the UTS namespace and how it gives a group of processes its own hostname.