CPU Affinity
On most systems, Linux included, the interface for setting CPU affinity uses a bitmask. A bitmask is a series of n bits, where each bit individually corresponds to the status of some other object. For example, CPU affinity (on 32-bit machines) is represented by a 32-bit bitmask. Each bit represents whether the given task is bound to the corresponding processor. Count the bits from right to left, bit 0 to bit 31 and, thus, processor zero to processor 31. For example:
11111111111111111111111111111111 = 4,294,967,295
is the default CPU affinity mask for all processes. Because all bits are set, the process can run on any processor. Conversely:
00000000000000000000000000000001 = 1is much more restrictive. Only bit 0 is set, so the process may run only on processor zero. That is, this affinity mask binds a process to processor zero.
Get it? What do the next two masks equal in decimal? What is the result of using them as the affinity mask of a process?
10000000000000000000000000000000 00000000000000000000000000000011
The first is equal to 2,147,483,648 and, because bit 31 is set, binds the process to processor number 31. The second is equal to 3, and it binds the process in question to processor zero and processor one.
The Linux CPU affinity interface uses a bitmask like that shown above. Unfortunately, C does not support binary constants, so you always have to use the decimal or hexadecimal equivalent. You may get a compiler warning for very large decimal constants that set bit 31, but they will work.
With the correct kernel and glibc in hand, using the system calls is easy:
#define _GNU_SOURCE
#include <sched.h>
long
sched_setaffinity(pid_t pid, unsigned int len,
unsigned long *user_mask_ptr);
long
sched_getaffinity(pid_t pid, unsigned int len,
unsigned long *user_mask_ptr);
The first system call is used to set the affinity of a process, and the second system call retrieves it.
In either system call, the PID argument is the PID of the process whose mask you wish to set or retrieve. If the PID is set to zero, the PID of the current task is used.
The second argument is the length in bytes of the CPU affinity bitmask, currently four bytes (32 bits). This number is included in case the kernel ever changes the size of the CPU affinity mask and allows the system calls to be forward-compatible with any changes; breaking syscalls is bad form, after all. The third argument is a pointer to the bitmask itself.
Let us look at retrieving the CPU affinity of a task:
unsigned long mask;
unsigned int len = sizeof(mask);
if (sched_getaffinity(0, len, &mask) < 0) {
perror("sched_getaffinity");
return -1;
}
printf("my affinity mask is: %08lx\n", mask);
As a convenience, the returned mask is binary ANDed against the mask of all processors in the system. Thus, processors in your system that are not on-line have corresponding bits that are not set. For example, a uniprocessor system always returns 1 for the above call (bit 0 is set and no others).
Setting the mask is equally easy:
unsigned long mask = 7; /* processors 0, 1, and 2 */
unsigned int len = sizeof(mask);
if (sched_setaffinity(0, len, &mask) < 0) {
perror("sched_setaffinity");
}
This example binds the current process to the first three processors in the system.
You then can call sched_getaffinity() to ensure the change took effect. What does sched_getaffinity() return for the above setup if you have only two processors? What if you have only one? The system call fails unless at least one processor in the bitmask exists. Using a mask of zero always fails. Likewise, binding to processor seven if you do not have a processor seven will fail.
It is possible to retrieve the CPU affinity mask of any process on the system. You can set the affinity of only the processes you own, however. Of course, root can set any process' affinity.
If you are not a programmer, or if you cannot modify the source for whatever reason, you still can bind processes. Listing 1 is the source code for a simple command-line utility to set the CPU affinity mask of any process, given its PID. As we discussed above, you must own the process or be root to do this.
Usage is simple; once you learn the decimal equivalent of the CPU mask, you need:
usage: bind pid cpu_mask
As an example, assume we have a dual computer and want to bind our Quake process (with PID 1600) to processor two. We would enter the following:
bind 1600 2
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- RSS Feeds
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Designing Electronics with Linux
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Validate an E-Mail Address with PHP, the Right Way
- What's the tweeting protocol?
- Kernel Problem
5 hours 4 min ago - BASH script to log IPs on public web server
9 hours 31 min ago - DynDNS
13 hours 7 min ago - Reply to comment | Linux Journal
13 hours 39 min ago - All the articles you talked
16 hours 3 min ago - All the articles you talked
16 hours 6 min ago - All the articles you talked
16 hours 7 min ago - myip
20 hours 32 min ago - Keeping track of IP address
22 hours 23 min ago - Roll your own dynamic dns
1 day 3 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
Evan Plaice
Thank you...
I have worked in the past on commercial flight simulators where everything relies on real time processing architectures (essentially 80's workstation multi-processor /w shared memory bus tech). I have always wondered what it would be like to leverage real-time processing capabilities on a PC without the OS getting in the way.
Not only did you give the best description of the application of affinity I've seen so far, you answered my 'how do you limit the os to one processor' question.
I can think of so many applications where this would be useful. Ex, performance testing that, for the first time, can be accurately measure without the margin of error typically included by os task switching on the same core.
I really hope that an affinity tool will eventually be added to the vanilla kernel. It would be hugely beneficial to have a tool like yours (with added capability to view affinity) that could easily manage processor affinity.
Check?
How can you determine on which processor a process is running?
htop
htop
setting the cpu affinity for 128 processors
HOw to set the affinity for 128 processors. Since thhe bit pattern is unsigned long only 32 bits can be set. I am not sure how to do it for number of cpus greater than 32.?
Help
Hi
i want to Linux to bind one or more processes to one or more processors using Java code.but i dont know is it possible thru java.Any help?
Re: Kernel Korner: CPU Affinity
Hi,
I was just wondering if there's a similar way to bind IRQ's to a specific processor? That way drivers designed for single CPU can be used safely on a SMP machine as well.
Mark.
Re: Kernel Korner: CPU Affinity
Just look at /proc/sys/irq/xx/smp_affinity
You can read about it in Documentation/filesystems/proc.txt