This is namespaces/cred_launcher.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/cred_launcher.c

  Cover of The Linux Programming Interface

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

/* cred_launcher.c

   Change the calling process's credentials to the numeric UID and GID
   provided by command-line options, and then launch the program (with
   arguments) specified in the remainder of the command line.

   A similar effect can be achieved using the setpriv(1) command:

        setpriv --reuid=1 --regid=1 --keep-group command [arg...]

   However, the program below also has an option (-v) to allow us to
   verify the process's capabilities before executing the command.
#define _GNU_SOURCE
#include <unistd.h>
#include "userns_functions.h"
#include "tlpi_hdr.h"
static void
usage(char *pname)
    fprintf(stderr, "Usage: %s [-u UID] [-g GID] [-v] command [arg...]\n",
main(int argc, char *argv[])
    /* Parse command-line options */

    uid_t newuid = -1;
    gid_t newgid = -1;
    int verbose = 0;
    int opt;
    while ((opt = getopt(argc, argv, "+g:u:v")) != -1) {
        switch (opt) {
        case 'g': newgid = atoi(optarg);        break;
        case 'u': newuid = atoi(optarg);        break;
        case 'v': verbose = 1;                  break;
        default:  usage(argv[0]);

    if (argc <= optind)

    /* Change process credentials as per the options */

    if (newgid != -1) {
        if (setresgid(newgid, newgid, newgid) == -1)

    if (newuid != -1) {
        if (setresuid(newuid, newuid, newuid) == -1)

    /* The '-v' option allows us to verify the capabilities of the process,
       which may have been modified as a consequence of UID changes */

    if (verbose)

    /* Execute the command specified in the remaining arguments */

    execvp(argv[optind], &argv[optind]);



Download namespaces/cred_launcher.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