This is namespaces/demo_userns.c, an example to accompany the book, The Linux Programming Interface.

This file is not printed in the book; it demonstrates Linux features that are not described in the book (typically features that have appeared since the book was published).

The source code file is copyright 2022, Michael Kerrisk, and is licensed under the GNU General Public License, version 3.

In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.


Download namespaces/demo_userns.c

  Cover of The Linux Programming Interface

Function list (Bold in this list means a function is not static)

/* demo_userns.c

   Demonstrate the use of the clone() CLONE_NEWUSER flag.

   Link with "-lcap" and make sure that the "libcap-devel" (or
   similar) package is installed on the system.

#define _GNU_SOURCE
#include <sys/capability.h>
#include <sys/wait.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>

#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
                        } while (0)
static int                      /* Startup function for cloned child */
childFunc(void *arg)

    for (;;) {
        printf("eUID = %ld; eGID = %ld; ",
                (long) geteuid(), (long) getegid());

        cap_t caps = cap_get_proc();
        if (caps == NULL)

        char *str = cap_to_text(caps, NULL);
        if (str == NULL)

        printf("capabilities: %s\n", str);


        if (arg == NULL)


    return 0;

#define STACK_SIZE (1024 * 1024)
main(int argc, char *argv[])
    char *stack = mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE,
                 MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
    if (stack == MAP_FAILED)

    /* Create child; child commences execution in childFunc() */

    pid_t pid = clone(childFunc,
                    stack + STACK_SIZE, /* Assume stack grows downward */
                    CLONE_NEWUSER | SIGCHLD, argv[1]);
    if (pid == -1)

    printf("PID of child: %ld\n", (long) pid);

    /* Parent falls through to here.  Wait for child. */

    if (waitpid(pid, NULL, 0) == -1)



Download namespaces/demo_userns.c

Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.

Valid XHTML 1.1