Unix & Linux
linux namespace unshare
Updated Wed, 21 Sep 2022 11:29:20 GMT

How do you get the child pid of `unshare` when using --fork for `nsenter -t <pid>`?


When using unshare --pid --fork, the nsenter command must attach to the child pid not the unshare pid to get to the right pid namespace.

I can get unshare's pid as follows:

unshare --pid --mount --fork --mount-proc  bash & 
echo PID: $!
fg

but I need unshare's child's pid (2914003) to enter the right namespace:

ps wwfuax | grep -A1 unshare 
2914002 pts/4    S      0:00  |           \_ unshare --pid --mount --fork --mount-proc bash
2914003 pts/4    S+     0:00  |               \_ bash

This works: nsenter -t 2914003 This does not: nsenter -t 2914002

I was hoping for some kind of option like unshare --show-child-pid but there isn't.

What is a nice reliable way to get unshare's child's pid?




Solution

The best solution is to not rely on process ids.

When you use the unshare command to create namespaces, you can create persistent namespaces that are referred to by a bind mount on the filesystem. We can set that up following the example in the unshare(1) man page.

First, we need to set up a mountpoint with private propagation:

mkdir /tmp/ns
mount --bind /tmp/ns /tmp/ns
mount --make-private /tmp/ns

And then we need target files for our mount and pid namespaces:

touch /tmp/ns/{mnt,pid}

Now we create our namespaces with the unshare command:

unshare --pid=/tmp/ns/pid --mount=/tmp/ns/mnt --fork --mount-proc  bash

Using those reference mountpoints, we can enter the namespaces with no knowledge of process ids:

nsenter --mount=/tmp/ns/mnt --pid=/tmp/ns/pid

When you're done, don't forget to clean up:

umount /tmp/ns/{mnt,pid}




Comments (2)

  • +0 – Nice one. I was stuck by the fact that /proc in the correct namespace(s) was not available to retrieve this information beside /proc/PID/ns/pid_for_children which gives only the pid namespace and isn't useful without its associated mount namespace. — Jul 23, 2022 at 13:47  
  • +0 – I think thats what I was trying here, can you check this question and see what I was doing wrong: unix.stackexchange.com/questions/710809/… — Jul 24, 2022 at 20:29