4

Is there any way to get CPU number of current task? (What I need is not the number of CPUs the task is running on, but which CPU the task is running on)

This process must be in kernel-level, therefore something like command line won't help.

I am trying to do this by calling kernel functions or using kernel data structures(like task_struct), but I am having trouble.

1
  • You might want to copy that answer into a new answer here (including the link to the source, of course). Commented Dec 24, 2017 at 16:39

3 Answers 3

2

A rather old question but this might be helpful for the future:

If you have CONFIG_THREAD_INFO_IN_TASK enabled (which is usually the default) then you can simply access the current CPU of the task using the cpu member of task_struct: current->cpu

As you can find in the source:

#ifdef CONFIG_THREAD_INFO_IN_TASK /* Current CPU: */ unsigned int cpu; #endif 

And also the previous CPU of the task as could be found in task_struct:

 /* * recent_used_cpu is initially set as the last CPU used by a task * that wakes affine another task. Waker/wakee relationships can * push tasks around a CPU where each wakeup moves to the next one. * Tracking a recently used CPU allows a quick search for a recently * used CPU that may be idle. */ int recent_used_cpu; 

You may also use cpu = task_cpu(p) which return id of the CPU.

Each task is also associated with a runqueue of a CPU. and each runqueue has a cpu field. The runqueue could be simply retrieved by rq = task_rq(p) and then rq->cpu.

Sign up to request clarification or add additional context in comments.

Comments

0

The sched_getcpu() "determine CPU on which the calling thread is running" function appears to exist solely to provide this.

http://man7.org/linux/man-pages/man3/sched_getcpu.3.html

1 Comment

That's a user-space function, the OP was asking for a kernel-space function.
-1

CPU details of processes are in /proc/[pid]/stat 39th field gives last CPU number where it was executed.

(39) processor %d (since Linux 2.2.8) CPU number last executed on.

For more details: http://man7.org/linux/man-pages/man5/proc.5.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.