On Linux, how do I the check CPU affinity of a process and its threads?

  • Why are you doing this? For a multithreaded process where you care about affinity, couldn't you use taskset to execute or leverage cgroups so the children all respect the affinities? – ewwhite Jan 2 '13 at 23:27
  • @ewwhite I'm doing this to check the affinity after setting them. I'm not asking about how or why to set the affinity. – JamesThomasMoon Feb 7 '13 at 0:10
  • O I C... Actually, not really. You haven't explained why you're looking for this info. – ewwhite Feb 7 '13 at 0:27
  • @ewwhite The why is to verify a program's threads have affinity set as expected. These are mostly-independent processing threads on a multicore machine. – JamesThomasMoon Feb 8 '13 at 6:04

It's pretty simple. Gather the all process id and thread ids then call program taskset. Like,

taskset -cp 2
taskset -cp 4

print all by process name

taskset has the --all-tasks optional argument

taskset --all-tasks -p $(pgrep java)

For some processes, the --all-tasks doesn't appear to print all of the child processes (in my testing, it didn't print child processes for kthreadd, I'm not sure why that is).

print all by process name helper script

Here is a short Linux shell script to print CPU affinity for a process by name and all of it's child threads.

#!/usr/bin/env bash

set -eu

pname=${1:-kthreadd}  # default to 'kthreadd'
for pid in $(pgrep "${pname}"); do
    echo "PID: ${pid} (${pname})"
    for tid in $(pgrep -P "${pid}" | tr '\n' ' '); do
        taskset -cp "${tid}"


PID: 2 (kthreadd)
pid 4's current affinity list: 0
pid 6's current affinity list: 0
pid 7's current affinity list: 0
pid 8's current affinity list: 0

Tested on Ubuntu 12, bash 4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.