sched_setaffinity(2)
๐ sched_setaffinity(2) โ System Calls Manual ๐
okay bestie, gather round, because today we're talking about the โจ sched_setaffinity โจ and โจ sched_getaffinity โจ system calls โ that's the <pink>System Calls Manual</pink>, section 2, if you're keeping track. This is the whole "which CPUs is my thread even allowed to run on" situation, and ngl it's lowkey iconic.
๐ธ NAME ๐ธ
sched_setaffinity, sched_getaffinity โ set and get a thread's CPU affinity mask ๐
๐ LIBRARY ๐
Standard C library (libc, -lc) ๐ซถ
โจ SYNOPSIS โจ
okay so first things first, you gotta have _GNU_SOURCE defined or none of this is happening, fr fr:
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <sched.h>
int sched_setaffinity(pid_t pid, size_t cpusetsize,
const cpu_set_t *mask);
int sched_getaffinity(pid_t pid, size_t cpusetsize,
cpu_set_t *mask);
๐ DESCRIPTION ๐
So. A thread's CPU affinity mask is literally just the set of CPUs it's eligible to run on. That's it, that's the whole vibe. And on a multiprocessor system, setting that mask can actually get you some real performance benefits. Like, for example: dedicate one single CPU to a particular thread โ meaning you set that thread's affinity mask to exactly one CPU, and then set the affinity mask of every other thread to exclude that CPU โ and boom, you've basically guaranteed maximum execution speed for that special thread. Main character energy, honestly. ๐
Also? Restricting a thread to run on a single CPU means you avoid the performance cost that comes from cache invalidation โ the sad little thing that happens when a thread stops running on one CPU and then starts up again on a different CPU. So rude of the scheduler to do that to it.
A CPU affinity mask is represented by the cpu_set_t structure โ a "CPU set" โ which is the thing mask points to. There's a whole family of macros for poking at CPU sets, and those are described over in CPU_SET(3). Go look, it's a good time.
<sched_setaffinity>sched_setaffinity()</sched_setaffinity> sets the CPU affinity mask of the thread whose ID is pid to whatever value you put in mask. And if pid is zero, then it's the calling thread we're talking about. The cpusetsize argument is the length (in bytes) of the data that mask points to. Normally you'd just pass sizeof(cpu_set_t) there, easy peasy.
And here's a cute detail: if the thread specified by pid isn't currently running on one of the CPUs listed in mask, then that thread gets migrated to one of the CPUs specified in mask. Like, pack your bags bestie, we're moving. ๐ฆ
<sched_getaffinity>sched_getaffinity()</sched_getaffinity> does the opposite โ it writes the affinity mask of the thread whose ID is pid into the cpu_set_t structure pointed to by mask. The cpusetsize argument here specifies the size (in bytes) of mask. And again, if pid is zero, you get back the mask of the calling thread.
๐ RETURN VALUE ๐
On success, sched_setaffinity() and sched_getaffinity() return 0. But wait โ there's a lil plot twist, so peep the "C library/kernel differences" section down below, because the underlying sched_getaffinity() is not the same girl when it comes to return value. ๐
On failure, -1 is returned, and errno gets set to tell you what went wrong.
๐ ERRORS ๐
EFAULTโ A supplied memory address was invalid. Like girl, that pointer is not pointing anywhere valid. ๐ญEINVALโ The affinity bit maskmaskcontains no processors that are currently physically on the system and permitted to the thread, according to any restrictions that may be imposed bycpusetcgroups or the"cpuset"mechanism described incpuset(7).EINVALโ (sched_getaffinity()and, before Linux 2.6.9,sched_setaffinity())cpusetsizeis smaller than the size of the affinity mask used by the kernel. Your buffer is too smol, bestie. ๐EPERMโ (sched_setaffinity()) The calling thread does not have appropriate privileges. The caller needs an effective user ID equal to the real user ID or effective user ID of the thread identified bypid, or it must possess theCAP_SYS_NICEcapability in the user namespace of the threadpid. iykyk โ no perms, no party. ๐ESRCHโ The thread whose ID ispidcould not be found. She's not here, she's gone, ๐.
๐ STANDARDS ๐
Linux. That's it. That's the standard. โจ
๐ HISTORY ๐
- Linux
2.5.8, glibc2.3. - So initially, the glibc interfaces included a
cpusetsizeargument, and it was typed asunsigned int. Then in glibc2.3.3, thecpusetsizeargument got removed โ but then it was restored in glibc2.3.4, this time with typesize_t. Not the glow-up arc nobody expected. ๐
๐ NOTES ๐
So after you call sched_setaffinity(), the set of CPUs your thread will actually run on is the intersection of the set you specified in the mask argument and the set of CPUs that are actually present on the system. And the system can restrict it even more if the "cpuset" mechanism from cpuset(7) is in play. All these restrictions on the actual set of CPUs your thread runs on? Silently imposed by the kernel. No warning, no note, it just does it. ๐
There's a bunch of ways to figure out how many CPUs are available on your system, including:
- inspecting the contents of
/proc/cpuinfo; - using
sysconf(3)to obtain the values of the_SC_NPROCESSORS_CONFand_SC_NPROCESSORS_ONLNparameters; - and inspecting the list of CPU directories under
/sys/devices/system/cpu/.
sched(7) has a description of the Linux scheduling scheme, if you wanna go deeper.
Also important: the affinity mask is a per-thread attribute, meaning it can be adjusted independently for each of the threads in a thread group. The value returned from a call to gettid(2) can be passed in the argument pid. Specifying pid as 0 will set the attribute for the calling thread, and passing the value returned from a call to getpid(2) will set the attribute for the main thread of the thread group. And pssst โ if you're using the POSIX threads API, then use pthread_setaffinity_np(3) instead of sched_setaffinity(). Just do it, trust. ๐ซถ
The isolcpus boot option can be used to isolate one or more CPUs at boot time, so that no processes are scheduled onto those CPUs. After you use this boot option, the only way to schedule processes onto the isolated CPUs is via sched_setaffinity() or the cpuset(7) mechanism. For more info, see the kernel source file Documentation/admin-guide/kernel-parameters.txt. And as noted in that file, isolcpus is the preferred mechanism of isolating CPUs โ versus the alternative of manually setting the CPU affinity of every single process on the system. Yeah. Nobody has time for that. ๐ญ
A child created via fork(2) inherits its parent's CPU affinity mask. And the affinity mask is preserved across an execve(2). Slay, continuity. โจ
๐ง C library/kernel differences ๐ง
This manual page describes the glibc interface for the CPU affinity calls. The actual system call interface is slightly different โ the mask is typed as unsigned long *, which reflects the fact that the underlying implementation of CPU sets is a simple bit mask. Same energy, different outfit. ๐
On success, the raw sched_getaffinity() system call returns the number of bytes placed copied into the mask buffer; this will be the minimum of cpusetsize and the size (in bytes) of the cpumask_t data type that is used internally by the kernel to represent the CPU set bit mask. (Yes, that sentence says "placed copied". We keep it verbatim, bestie, we don't rewrite lore. ๐ซถ)
๐ Handling systems with large CPU affinity masks ๐
Okay here's where it gets hairy. The underlying system calls โ which represent CPU masks as bit masks of type unsigned long * โ impose no restriction on the size of the CPU mask. However! The cpu_set_t data type used by glibc has a fixed size of 128 bytes, meaning the maximum CPU number that can be represented is 1023.
So if the kernel CPU affinity mask is larger than 1024, then calls of the form:
sched_getaffinity(pid, sizeof(cpu_set_t), &mask);
fail with the error EINVAL โ which is the error produced by the underlying system call for the case where the mask size specified in cpusetsize is smaller than the size of the affinity mask used by the kernel. And depending on the system CPU topology, the kernel affinity mask can be substantially larger than the number of active CPUs in the system. So like, way bigger. ๐ณ
When you're working on systems with large kernel CPU affinity masks, you must dynamically allocate the mask argument โ see CPU_ALLOC(3). And currently, the only way to do this is by probing for the size of the required mask using sched_getaffinity() calls with increasing mask sizes, until the call does not fail with the error EINVAL. It's giving trial and error, but make it system calls.
โ ๏ธ Be aware thatCPU_ALLOC(3)may allocate a slightly larger CPU set than requested โ because CPU sets are implemented as bit masks allocated in units ofsizeof(long). Consequently,sched_getaffinity()can set bits beyond the requested allocation size, because the kernel sees a few additional bits. So the caller should iterate over the bits in the returned set, counting those which are set, and stop upon reaching the value returned byCPU_COUNT(3)โ rather than iterating over the number of bits requested to be allocated. Do not skip this, bestie, it will bite you. ๐
๐ฅ EXAMPLES ๐ฅ
The program below creates a child process. The parent and child then each assign themselves to a specified CPU and execute identical loops that consume some CPU time. Before terminating, the parent waits for the child to complete. The program takes three command-line arguments: the CPU number for the parent, the CPU number for the child, and the number of loop iterations that both processes should perform.
As the sample runs below demonstrate, the amount of real and CPU time consumed when running the program will depend on intra-core caching effects and whether the processes are using the same CPU. ๐
We first employ lscpu(1) to determine that this (x86) system has two cores, each with two CPUs:
$ lscpu | egrep -i 'core.*:|socket';
Thread(s) per core: 2
Core(s) per socket: 2
Socket(s): 1
We then time the operation of the example program for three cases: both processes running on the same CPU; both processes running on different CPUs on the same core; and both processes running on different CPUs on different cores.
$ time -p ./a.out 0 0 100000000;
real 14.75
user 3.02
sys 11.73
$ time -p ./a.out 0 1 100000000;
real 11.52
user 3.98
sys 19.06
$ time -p ./a.out 0 3 100000000;
real 7.89
user 3.29
sys 12.07
๐ธ Program source ๐ธ
okay here's the full source, character-for-character, don't @ me:
#define _GNU_SOURCE
#include <err.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{
int parentCPU, childCPU;
cpu_set_t set;
unsigned int nloops;
if (argc != 4) {
fprintf(stderr, "Usage: %s parent-cpu child-cpu num-loops\n",
argv[0]);
exit(EXIT_FAILURE);
}
parentCPU = atoi(argv[1]);
childCPU = atoi(argv[2]);
nloops = atoi(argv[3]);
CPU_ZERO(&set);
switch (fork()) {
case -1: /* Error */
err(EXIT_FAILURE, "fork");
case 0: /* Child */
CPU_SET(childCPU, &set);
if (sched_setaffinity(0, sizeof(set), &set) == -1)
err(EXIT_FAILURE, "sched_setaffinity");
for (unsigned int j = 0; j < nloops; j++)
getppid();
exit(EXIT_SUCCESS);
default: /* Parent */
CPU_SET(parentCPU, &set);
if (sched_setaffinity(0, sizeof(set), &set) == -1)
err(EXIT_FAILURE, "sched_setaffinity");
for (unsigned int j = 0; j < nloops; j++)
getppid();
wait(NULL); /* Wait for child to terminate */
exit(EXIT_SUCCESS);
}
}
๐ part 2 incoming, bestie โ do NOT close the tab, there's more tea to spill ๐
๐ญ SEE ALSO โ aka ur reading list bestie โจ
okay so you survived the whole page ๐ which, slay, honestly. But no page is an island and this one is literally holding hands with a whole friend group of other man pages. Go say hi. They're all one man away, no cap:
the section 1 girlies (user commands, ur fave little CLI besties)
the section 2 girlies (syscall central, main character energy fr)
clone(2)getcpu(2)getpriority(2)gettid(2)nice(2)sched_get_priority_max(2)sched_get_priority_min(2)sched_getscheduler(2)sched_setscheduler(2)setpriority(2)
the section 3 girlies (library calls, the ones u actually #include)
the section 7 girlies (big-picture overviews, the lore ๐ )
the section 8 girly (sysadmin territory, respect)
ngl bestie, if u only click ONE thing from this list, make itsched(7)โ it's the whole scheduling saga in one sitting and u will โจunderstand thingsโจ. And if ur vibe check says "wait, what CPUs do I even have", that'slscpu(1)andnproc(1)knocking on ur door ๐ซถ
k that's literally the whole page, we made it to the end together ๐ญ๐ this little beauty comes from Linux man-pages 6.20, dated 2026-02-08, and it lives under the name sched_setaffinity(2) โ say it with me one time for the girlies ๐ periodt, go bind urself to a CPU and thrive ๐ฆโจ
๐ฆ where this page comes from
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages 6.20
- ๐ the page's license: GPL-2.0-or-later
- Copyright 2002, Robert Love <rlove@rlove.org>
- Copyright 2006-2015, Michael Kerrisk <mtk.manpages@gmail.com>
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms