Taskset Command for CPU Affinity in Linux

This article provides an overview of the Linux taskset command, detailing how it manages CPU affinity by binding processes to specific processor cores. It covers the core functionality of the command, the concept of processor affinity, practical command syntax for both running and new processes, and the performance benefits of controlling CPU scheduling.

Understanding CPU Affinity

CPU affinity, or processor affinity, is a scheduling feature that binds a process or thread to one or more designated CPU cores. By default, the Linux kernel scheduler dynamically assigns tasks to any available CPU core to balance the overall system workload. However, frequently moving a process between different cores can lead to performance overhead due to CPU cache invalidation. Setting CPU affinity ensures that a process runs exclusively on the assigned cores, preserving cache locality and reducing latency.

The Function of the taskset Command

The taskset command is a standard Linux utility (part of the util-linux package) used to retrieve and manipulate the CPU affinity of a process. It operates either by modifying the CPU mask of an already running process using its Process ID (PID) or by launching a new process with a predefined core assignment.

CPU affinity can be specified in two formats:

Common Usage and Syntax

Checking the Current Affinity of a Process

To view which cores are assigned to an active process:

taskset -p <PID>

To display the affinity in a readable core list format:

taskset -cp <PID>

Changing the Affinity of a Running Process

To reassign an existing process to specific cores (such as cores 1 and 3):

taskset -cp 1,3 <PID>

Launching a Process with Specific Affinity

To start an application bound strictly to designated cores (for example, cores 0 and 2):

taskset -c 0,2 <command> <arguments>

Key Use Cases and Benefits