procpri/t_sched_setaffinity.cThis 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 2024, 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.
|
/* 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"
int 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; CPU_ZERO(&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) errExit("sched_setaffinity"); exit(EXIT_SUCCESS); }
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.