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: $!

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?

  • 2
    Does pgrep -P pid-of-parent-process-here find the right pid (or pids)?
    – thrig
    Jul 23, 2022 at 4: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, 2022 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, 2022 at 20:28

1 Answer 1


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}
  • 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, 2022 at 13:47
  • 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/…
    – KJ7LNW
    Jul 24, 2022 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.