Reputation: 31
In my server, there exists several CPUs (0-7). I need run parallel code, and each process affiliate with one CPU, so how do I know the CPU information for each process?
For example, if two processes (#0 and #1) exist, and process #0 uses CPU 5 and process #1 uses CPU 7.
how do I know that by programming in C or Fortran?
Upvotes: 3
Views: 2184
Reputation: 51465
Generally, you have to change the CPU affinity, because a process can migrate between processors: CPU Affinity (Linux Journal, 2003).
Upvotes: 0
Reputation: 5540
I'm not aware of any system call on Linux that will give you general information about what CPU a thread in running on. @nos is correct that sched_getcpu() will tell you which CPU a thread is running on, but only for the calling context.
You can do this by querying the /proc
file system. However, if you find yourself building your application around this functionality, it is likely that you need to reexamine your design.
The file /proc/<pid>/stats
contains a field that provides you with the last CPU the process ran on. You would just need to parse the output. (use man proc
to see the field list).
Upvotes: 2
Reputation: 229098
Use the sched_getcpu() call.
Keep in mind that a process/thread can be scheduled freely to run on any available cpu/core, so one of your processes could run on core 1 one second, and on core 2 the next milisecond. You can restrict which processors a process is allowed to run on with sched_setaffinity()
Upvotes: 2
Reputation: 10642
In general it is the task of the operating system to abstract such things from applications. Normally I see my applications (as simple as doing a grep on a huge file) change CPU core every once in a while.
Now if you want to force an application on a specific core you can manually set the CPU affinity.
I've written some pretty strange software in the past and I've never had the desire to know and/or control this.
Why would you want to know?
Upvotes: 1
Reputation: 18998
More generally, why do you want to know? The Linux kernel is very good at scheduling processes/threads to make the best use of the available cores.
Upvotes: 0