How to limit a process to one CPU core in Linux?
Under Linux, execute the sched_setaffinity
system call. The affinity of a process is the set of processors on which it can run. There's a standard shell wrapper: taskset
. For example, to pin a process to CPU #0 (you need to choose a specific CPU):
taskset -c 0 mycommand --option # start a command with the given affinity
taskset -c -pa 0 1234 # set the affinity of a running process
There are third-party modules for both Perl (Sys::CpuAffinity
) and Python (affinity
) to set a process's affinity. Both of these work on both Linux and Windows (Windows may require other third-party modules with Sys::CpuAffinity
); Sys::CpuAffinity
also works on several other unix variants.
If you want to set a process's affinity from the time of its birth, set the current process's affinity immediately before calling execve
. Here's a trivial wrapper that forces a process to execute on CPU 0.
#!/usr/bin/env perl
use POSIX;
use Sys::CPUAffinity;
Sys::CpuAffinity::setAffinity(getpid(), [0]);
exec $ARGV[0] @ARGV
You can build cpu-sets on the command line as well. man cpuset
Later on you can assign (running) processes to these.