简体   繁体   中英

How to get the CPU information of a process in Linux?

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?

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 ()

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).

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?

通常,您必须更改CPU亲和性,因为进程可以在处理器之间进行迁移: CPU Affinity (Linux Journal,2003)。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM