setns() — Linux system interface
Reassociate the calling thread with an existing namespace identified by a namespace descriptor (or supported pidfd form with a namespace-type mask). For a namespace descriptor, nstype selects an expected type or zero to accept the descriptor type. Rules and required capabilities depend on namespace type and current credentials; EPERM, EINVAL and EBADF are possible. Joining a PID namespace affects subsequently created children rather than the caller PID. The VM-only program uses only the current process UTS namespace descriptor to demonstrate the call and unchanged identity; it does not join another process or demonstrate migration. Even this re-association may require CAP_SYS_ADMIN. Compile-only here; run only in an authorized disposable VM, not production, and never bypass sandbox restrictions. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; Runtime NOT RUN locally. In the authorized VM only, run ./example --authorized-vm with a timeout after review. Linux-specific interface or flags; examples target Linux/glibc on x86_64. These are libc-facing signatures, not raw architecture-specific syscall ABIs.
Formal Syntax & Structure
#define _GNU_SOURCE#include <sched.h>int setns(int fd, int nstype);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fd | int | Open namespace descriptor or supported pidfd. |
| nstype | int | Namespace type for namespace fd, or supported mask for pidfd. |
Return Value
0 on success. On failure, returns -1 and sets errno.
Working Example
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sched.h>#include <fcntl.h>#include <sys/stat.h>#include <string.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \ fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \ return EXIT_FAILURE; \} } while (0)
int main(int argc, char **argv){ /* Explicit opt-in is not a security boundary: use only an authorized disposable VM. */ CHECK(argc == 2 && strcmp(argv[1], "--authorized-vm") == 0); int fd = open("/proc/self/ns/uts", O_RDONLY | O_CLOEXEC); CHECK(fd >= 0); struct stat before, after; CHECK(fstat(fd, &before) == 0); CHECK(setns(fd, CLONE_NEWUTS) == 0); CHECK(stat("/proc/self/ns/uts", &after) == 0); CHECK(before.st_dev == after.st_dev && before.st_ino == after.st_ino); CHECK(close(fd) == 0); puts("own UTS namespace reassociated; identity unchanged"); return EXIT_SUCCESS;}