golang could not unix.Setns user namespace, throw invalid argument error

23 views
Skip to first unread message

doubled lin

unread,
12:45 PM (9 hours ago) 12:45 PM
to golang-nuts
test code:
```
package main

import (
"fmt"
"os"
"runtime"

"golang.org/x/sys/unix"
)

func main() {
targetPid := "2356795"

runtime.LockOSThread()
defer runtime.UnlockOSThread()

userNsPath := fmt.Sprintf("/proc/%s/ns/user", targetPid)
fd, err := os.Open(userNsPath)
if err != nil {
fmt.Printf("Failed to open user namespace: %v\n", err)
return
}
defer fd.Close()

if err := unix.Setns(int(fd.Fd()), unix.CLONE_NEWUSER); err != nil {
fmt.Printf("Failed to setns: %v\n", err)
return
}

fmt.Println("Successfully entered user namespace")

ns, err := os.Readlink("/proc/self/ns/user")
if err != nil {
fmt.Printf("Failed to read /proc/self/ns/user: %v\n", err)
return
}
fmt.Println("Current /proc/self/ns/user:", ns)
}
```
run error:
Failed to setns: invalid argument

what's wrong with me?

thanks in advantage

Reto

unread,
3:23 PM (6 hours ago) 3:23 PM
to golan...@googlegroups.com
On Mon, Jan 26, 2026 at 12:18:20AM -0800, doubled lin wrote:
> Failed to setns: invalid argument
>
> what's wrong with me?

With you? Nothing.
Go spawns additional threads in the runtime however.
The syscall you try to execute only works if a process didn't fork(2) et al
as specified in the syscall docs, which leads to the failure return.

https://github.com/golang/go/issues/10051

Jason E. Aten

unread,
3:25 PM (6 hours ago) 3:25 PM
to golang-nuts
A guess:
(from the man page for setns(2), on Ubuntu 24.04):
"A multithreaded process  may  not  change  user  namespace  with setns()."

Go processes are always multithreaded, unless you are using wasm/wasi, but then
you would not have access to golang.org/x/sys/unix anyway.

Also the man page says that the fd should be in /proc/pid/ns, so I'm not sure if /proc/pid/ns/user counts.
I would write a single threaded C program to check that. An LLM could generate one for you in a moment.
Reply all
Reply to author
Forward
0 new messages