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

This file is not printed in the book; it is a supplementary file for Chapter 35.

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 procpri/t_sched_setaffinity.c

  Cover of The Linux Programming Interface

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

/* t_sched_setaffinity.c

   Usage: t_sched_setaffinity pid mask

   Set the CPU affinity of the process identified by 'pid' according
   to the given 'mask'. For example, the following specifies that the
   given process should run on any but the first CPU of a 4-CPU system:

        t_sched_setaffinity <pid> 0xe

                (0xe = 1110 binary)

   See also t_sched_getaffinity.c.

   This program is Linux-specific. The CPU affinity system calls are provided
   since kernel 2.6.
#define _GNU_SOURCE
#include <sched.h>
#include "tlpi_hdr.h"
main(int argc, char *argv[])

    if (argc != 3 || strcmp(argv[1], "--help") == 0)
        usageErr("%s pid mask\n", argv[0]);

    pid_t pid = getInt(argv[1], GN_NONNEG, "pid");
    unsigned long mask = getLong(argv[2], GN_ANY_BASE, "octal-mask");

    cpu_set_t set;

    for (int cpu = 0; mask > 0; cpu++, mask >>= 1)
        if (mask & 1)
            CPU_SET(cpu, &set);

    if (sched_setaffinity(pid, sizeof(set), &set) == -1)



Download procpri/t_sched_setaffinity.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