Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

How do I check CPU Affinity for a linux processes and all of it's threads?

share|improve this question
    
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. –  JamesThomasMoon1979 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. –  JamesThomasMoon1979 Feb 8 '13 at 6:04
add comment

1 Answer 1

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

pname="apache2" # for example
for pid in $(pgrep "${pname}") ; do 
    [ "${pid}" != "" ] || exit
    echo "PID: ${pid}"
    for tid in \
          $(ps --no-headers -ww -p "${pid}" -L -olwp | sed 's/$/ /' | tr  -d '\n') ; do
        taskset -cp "${tid}"  # substitute thread id in place of a process id
    done
done

The reason this is not a simple one-liner is because the pgrep command cannot return thread ids (only process ids). We do a little extra work with the command ps --no-headers -ww -p "${pid}" -L -olwp

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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