11

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

4
  • 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, 2013 at 23:27
  • 1
    @ewwhite I'm doing this to check the affinity after setting them. I'm not asking about how or why to set the affinity. Feb 7, 2013 at 0:10
  • O I C... Actually, not really. You haven't explained why you're looking for this info.
    – ewwhite
    Feb 7, 2013 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. Feb 8, 2013 at 6:04

1 Answer 1

14

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}"
    done
done

Outputs

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .