In this lesson, you will learn how to shift an already running process into a different isolation domain by joining its existing namespaces.
The Concept of Namespace Migration
While we often think of namespaces as boundaries set during the birth of a process (via clone or unshare), Linux allows processes to "join" existing namespaces. This is primarily done using the setns() system call. When a process joins a namespace, it effectively drops its current view of the world (like its network stack or PID environment) and adopts the view of the target namespace.
Think of this like changing rooms in a secure facility: you leave your old office and walk into a new one, inheriting the rules and resources of that new space.
How it Works
To migrate a process, you need a handle for the target namespace. These are represented as special files located in /proc/[pid]/ns/. For example, to join the network namespace of another process, you would point to /proc/[pid]/ns/net.
The nsenter utility is the standard tool for this. Under the hood, it opens the namespace file and uses setns() to transition the process.
# Enter the network namespace of a target process (PID 1234)
sudo nsenter --target 1234 --net /bin/bash
Critical Risks and Constraints
Moving a process is powerful, but it comes with strict limitations:
- Threaded Risks: If a process is multi-threaded, you cannot change its PID namespace. The kernel prevents this because a process cannot belong to two different PID namespaces simultaneously, and changing the namespace of one thread while others remain in the old one would cause catastrophic internal inconsistency.
- Resource Inconsistency: If a process is migrated into a new Mount namespace, its file descriptors remain valid, but the "root" or mount points it sees will suddenly shift. If the process expects a configuration file at
/etc/configand the new namespace lacks that specific mount, the process will fail to find its own dependencies. - State Mismatch: Migrating a process into a different IPC or Network namespace can break internal communication if the process has open sockets or shared memory segments tied to its original environment.
Key Takeaway: Process migration via setns allows dynamic reassignment of isolation domains, but it is strictly restricted for multi-threaded processes and carries a high risk of breaking file system or socket dependencies.