Home > Article > Backend Development > How to Access CPU Information in Linux Using the `cpuid` Instruction?
Accessing CPU Information on Linux Using the cpuid Instruction
In this question, a developer seeks to access CPU information in a Linux environment using a method akin to the _cpuinfo() function in the Windows API. The provided code attempts to utilize assembly instructions (cpuid) to retrieve this information, but the developer wishes to avoid the need for manual assembly.
The solution lies in utilizing the cpuid.h header file available when compiling code with GCC. This header declares two functions:
<code class="c">unsigned int __get_cpuid_max(unsigned int __ext, unsigned int *__sig); int __get_cpuid(unsigned int __level, unsigned int *__eax, unsigned int *__ebx, unsigned int *__ecx, unsigned int *__edx);</code>
The __get_cpuid_max function returns the highest supported input value for the cpuid instruction. You can specify __ext as either 0x0 for basic information or 0x8000000 for extended information.
The __get_cpuid function retrieves CPU information for a specified level and returns the data in the eax, ebx, ecx, and edx registers. It returns a non-zero value if successful and zero if the requested level is not supported.
Usage Example:
<code class="c">#include <stdio.h> #include <cpuid.h> int main() { unsigned int eax, ebx, ecx, edx; // Get maximum supported CPUID level unsigned int max_level = __get_cpuid_max(0x0, NULL); // Iterate over different CPUID levels for (unsigned int level = 0; level <= max_level; level++) { // Retrieve CPUID data for the current level __get_cpuid(level, &eax, &ebx, &ecx, &edx); printf("Level %u: EAX=%u, EBX=%u, ECX=%u, EDX=%u\n", level, eax, ebx, ecx, edx); } return 0; }</code>
The above is the detailed content of How to Access CPU Information in Linux Using the `cpuid` Instruction?. For more information, please follow other related articles on the PHP Chinese website!