Pin a Process to a Specific CPU with taskset on Linux
Run a command on chosen CPUs with taskset -c 0 cmd, and read a process's current list with taskset -pc PID. nproc follows the affinity, and a bad CPU number fails.
A benchmark or a noisy job should stay on one core, or off the cores that another service uses.
echo "cpus visible: $(nproc)"
taskset -pc $$
taskset -c 0 nproc
taskset -c 0 sh -c 'taskset -pc $$'
taskset -c 999 true
echo "exit: $?"cpus visible: 10
pid 643's current affinity list: 0-9
1
pid 647's current affinity list: 0
taskset: failed to set pid 649's affinity: Invalid argument
exit: 1taskset -c 0 command starts the command with an affinity mask of CPU 0. The run shows ten CPUs visible and an affinity of 0-9, then nproc printing 1 under taskset -c 0, because nproc counts the CPUs the process may use. The child shell reports 0 as its list. A CPU that does not exist, here 999, fails with Invalid argument and exit status 1. See taskset.
Affinity limits where a process may run and does not reserve the CPU, so other work can still use it. Children inherit the mask. A container with a CPU set may allow fewer CPUs than the machine has, which is why -c 999 is not the only way to fail.