4

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?

KJ7LNW
  • 273
  • 1
  • 8
  • 2
    Does `pgrep -P pid-of-parent-process-here` find the right pid (or pids)? – thrig Jul 23 '22 at 04:45
  • 1
    @thrig Changing it into `pgrep -o -P pid-of-parent-process-here` will give just one: the first (which will be pid 1 inside) – A.B Jul 23 '22 at 13:04
  • @thrig, it does! Awesome, I didn't know that pgrep trick. A.B gives a good -o option, too. – KJ7LNW Jul 24 '22 at 20:28

1 Answers1

5

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}
larsks
  • 32,449
  • 5
  • 54
  • 70
  • 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. – A.B Jul 23 '22 at 13:47
  • I think thats what I was trying here, can you check this question and see what I was doing wrong: https://unix.stackexchange.com/questions/710809/why-is-the-linux-command-unshare-pid-p-mount-m-not-creating-a-persistent-n – KJ7LNW Jul 24 '22 at 20:29