Part 4 of 7 · 3 min read
Three namespaces measured
Think of a student who moves to a new school in another town: the same person, a new class list, a new school name and a new set of phone lines. The old school still exists and still counts the student as enrolled in a different register. The analogy stops in one place: a student really moves, and a process stays on the same kernel.
In plain words: The program below calls unshare with the flags for UTS, PID and network, and then forks. The first child created after a PID unshare is the first process of the new PID namespace, so it sees itself as number 1. The child sets a host name and lists the network devices.
A worked example.
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
static void names(const char *who) {
char h[64];
gethostname(h, sizeof h);
printf("%-7s pid=%-6d hostname=%s\n", who, (int)getpid(), h);
fflush(stdout);
}
int main(void) {
names("before");
if (unshare(CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNET)) { perror("unshare"); return 1; }
pid_t c = fork(); /* first child of the new PID namespace */
if (c == 0) {
sethostname("box", 3);
names("child");
puts("child sees these network interfaces:");
fflush(stdout);
execlp("sh", "sh", "-c", "tail -n +3 /proc/net/dev | cut -d: -f1", (char *)0);
_exit(1);
}
waitpid(c, NULL, 0);
printf("parent sees the child as pid %d\n", (int)c);
names("after");
return 0;
}
Output on the test machine:
before pid=236 hostname=vm
child pid=1 hostname=box
child sees these network interfaces:
lo
parent sees the child as pid 237
after pid=236 hostname=box
Four facts show. The child has number 1 in its own namespace and number 237 on the parent's, the same process in two tables. Its host name is box. Its network has only the loopback device lo, with no connection to the outside (a real container would add a virtual cable, called a veth pair, to a bridge). And the parent's host name also changed to box, because unshare(CLONE_NEWUTS) moved the caller into the new UTS namespace as well. Only the PID flag works differently: it affects the children created afterwards, which is why the parent kept pid 236. The machine's real host name, seen from a shell outside the program, stayed vm.
The key lines. The first process of a PID namespace has number 1 and the duties of init: it adopts orphans and, if it ends, the kernel kills the whole namespace (Level 1). A container's main process is its number 1.
PID namespace
A PID namespace is a namespace in which process numbers form their own sequence, starting at 1. A process has one number in each namespace that contains it, and it sees only the processes of its own namespace and below.
Example: the child above is number 1 in the new namespace and number 237 in its parent's.
Check yourself:
1. Why did the child see itself as number 1?
2. Why did the parent's host name change?
3. Why had the network namespace only lo?