Search code examples
c++clinuxmanpage

How can I get a process to core mapping in C?


What library function can I call to get mapping of processes to cores or given a process id tell me what core it's running on, it ran last time, or scheduled to run. So something like this:

core 1:  14232,42323
core 2:  42213,63434,434
core 3:  34232,34314
core 4:  42325,6353,1434,4342
core 5:  43432,64535,14345,34233
core 6:  23242,53422,4231,34242
core 7:  78789
core 8:  23423,23124,5663

I sched_getcpu returns the core number of calling process. If there was a function that given a process id, would return the core number that would be good too but I have not found one. sched_getaffinity is not useful either; It just tells you given a process what cores it can run on which is not what I'm interested in.


Solution

  • Yes, the virtual file /proc/[pid]/stat seems to have this info: man 5 proc:

    /proc/[pid]/stat
          Status  information  about  the  process.   This is used by ps(1).  It is
          defined in /usr/src/linux/fs/proc/array.c.
          (...fields description...)
    
          processor %d (since Linux 2.2.8)
                          CPU number last executed on.
    

    on my dual core:

    cat /proc/*/stat | awk '{printf "%-32s %d\n", $2 ":", $(NF-5)}'
    (su):                            0
    (bash):                          0
    (tail):                          1
    (hd-audio0):                     1
    (chromium-browse):               0
    (bash):                          1
    (upstart-socket-):               1
    (rpcbind):                       1
    

    ..though I can't say if it's pertinent and/or accurate..