How to set CPU affinity for any process

book

Article ID: 167883

calendar_today

Updated On:

Products

XOS

Issue/Introduction

Describes how to manually set CPU affinity for any process using Linux native tools. Please note this method is neither supported nor tested and should be used only on user's responsibility.

Cause

Under specific conditions it might be better to have some processes tied to a specific CPU core and avoid them being moved from one core to another dynamically as is done by the kernel for most of processes.

Almost all processes on a Linux-based system are not tied to any specific CPU core unless:
1. Directly specified within the code of the application and requested to the OS kernel.
2. Tied to specific CPU(s) from OS level.

The solution presented below shows how to set CPU/core affinity for example process ID 1033.

Resolution

For all manipulations, the taskset command is being used. The taskset command is available on Linux and similar tools are available on other Unix-based systems.

The command syntax is:
taskset (util-linux 2.13-pre7)
usage: taskset [options] [mask | cpu-list] [pid | cmd [args...]]
set or get the affinity of a process

  -p, --pid                  operate on existing given pid
  -c, --cpu-list             display and specify cpus in list format
  -h, --help                 display this help
  -v, --version              output version information


To retreive mask of an existsing task:
# taskset -p 1033

pid 1033's current affinity mask: 3

To retreive mask of an existsing task in human readable format:
# taskset -pc 1033
pid 1033's current affinity list: 0,1


To set mask of an existsing task by specyfing CPU:
# taskset -pc 1 1033
pid 1033's current affinity list: 0,1
pid 1033's new affinity list: 1


There's also an option to use masks instead of specifying CPU cores. It's up to the user to choose preferred method.