sched_setaffinity -- set the CPU affinity mask for a process


#include <sched.h>

int sched_setaffinity(pid_t pid, unsigned int cpusetsize, cpu_set_t * mask);


sched_setaffinity() shall set the CPU affinity mask for a process.

The parameter pid specifies the ID for the process. If pid is 0, then the calling process is specified instead.

The parameter cpusetsize specifies the length of the data pointed to by mask, in bytes. Normally, this parameter is specified as sizeof(cpu_set_t).

The parameter mask specifies the new value for the CPU affinity mask. The structure pointed to by mask represents the set of CPUs on which the process may run. If mask does not specify one of the CPUs on which the specified process is currently running, then sched_setaffinity() shall migrate the process to one of those CPUs.

Setting the mask on a multiprocessor system can improve performance. For example, setting the mask for one process to specify a particular CPU, and then setting the mask of all other processes to exclude the CPU, dedicates the CPU to the process so that the process runs as fast as possible. This technique also prevents loss of performance in case the process terminates on one CPU and starts again on another, invalidating cache.

Return Value

On success, sched_setaffinity() shall return 0.

On failure, sched_setaffinity() shall return -1 and set errno as follows.



Bad address.


mask does not specify any processors that exist in the system, or cpusetsize is smaller than the kernel's affinity mask.


Insufficient privileges. The effective user ID of the process calling sched_setaffinity() is not equal to the user ID or effective user ID of the specified process, and the calling process does not have appropriate privileges.


The specified process could not be found.

See Also

sched_setscheduler(), sched_getaffinity().