This post provides information on how to set or retrieve the CPU affinity of running processes. The ‘taskset‘ command has been shipped with different package names from version-to-versions.
# cat /etc/redhat-release CentOS release 6.10 (Final)
# uname -a Linux geeksearch.mylabserver.com 2.6.32-754.23.1.el6.x86_64 #1 SMP Thu Sep 26 12:05:41 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
# rpm -qf /bin/taskset util-linux-ng-2.17.2-12.28.el6_9.2.x86_64
From ‘taskset’ manual page:
# man taskset .... DESCRIPTION taskset is used to set or retrieve the CPU affinity of a running process given its PID or to launch a new COMMAND with a given CPU affinity. CPU affinity is a scheduler prop- erty that "bonds" a process to a given set of CPUs on the system. The Linux scheduler will honor the given CPU affinity and the process will not run on any other CPUs. Note that the Linux scheduler also supports natural CPU affinity: the scheduler attempts to keep processes on the same CPU as long as practical for performance reasons. Therefore, forcing a specific CPU affinity is useful only in certain applications. The CPU affinity is represented as a bitmask, with the lowest order bit corresponding to the first logical CPU and the highest order bit corresponding to the last logical CPU. Not all CPUs may exist on a given system but a mask may specify more CPUs than are present. A retrieved mask will reflect only the bits that correspond to CPUs physically on the system. If an invalid mask is given (i.e., one that corresponds to no valid CPUs on the current system) an error is returned. The masks are typically given in hexadeci- mal.
Query CPU Affinity
To query the current affinity, use ‘-p
$ taskset -p 31564 pid 31564's current affinity mask: 64 $ taskset -pc 31564 pid 31564's current affinity list: 2,5,6
The affinity task is defined in hexadecimal format. And each bit with ‘1’ represents a CPU, with right most bit represents CPU # 0
CPU #0: 0x00000001 CPU #1: 0x00000002 CPU #2: 0x00000004 CPU #3: 0x00000008 CPU #0 and CPU #1: 0x00000003 CPU #2 and CPU #3: 0x0000000C All CPUs: 0xFFFFFFFF
For above example, hexadecimal 64 is ‘01100100‘, which is present as 6,5,2.
Set CPU Affinity
To set the CPU affinity for a running process, use ‘-c [cpu list]‘ option below:
$ taskset -pc 0,1 31564 pid 31564's current affinity list: 2,5,6 pid 31564's new affinity list: 0,1
For more information please check taskset manual:
$ man taskset