对于 Windows 7 和 2008 服务器,有 GetActiveProcessorGroupCount function。但是你有 2003 的服务器,所以它不是一个选项。
在 C++ 中,这需要编写 WMI 消费者代码,这是一种笨拙而无聊的 (D)COM 东西。
一个不错的解决方案是运行systeminfo 命令并解析输出,但要小心,因为输出的列标题已本地化为系统的区域设置。
编辑
刚刚找到了一个更好的解决方案,它利用 WMI 的命令行界面。
运行以下命令并解析输出,每个套接字有一行
> wmic.exe cpu get
AddressWidth Architecture Availability Caption ConfigManagerErrorCode ConfigManagerUserConfig CpuStatus CreationClassName CurrentClockSpeed CurrentVoltage DataWidth Description DeviceID ErrorCleared ErrorDescription ExtClock Family InstallDate L2CacheSize L2CacheSpeed L3CacheSize L3CacheSpeed LastErrorCode Level LoadPercentage Manufacturer MaxClockSpeed Name NumberOfCores NumberOfLogicalProcessors OtherFamilyDescription PNPDeviceID PowerManagementCapabilities PowerManagementSupported ProcessorId ProcessorType Revision Role SocketDesignation Status StatusInfo Stepping SystemCreationClassName SystemName UniqueId UpgradeMethod Version VoltageCaps
64 9 3 Intel64 Family 6 Model 23 Stepping 6 1 Win32_Processor 2532 33 64 Intel64 Family 6 Model 23 Stepping 6 CPU0 421 2 0 0 6 1 GenuineIntel 2532 Intel(R) Core(TM)2 Duo CPU T9400 @ 2.53GHz 2 2 FALSE BFEBFBFF00010676 3 5894 CPU CPU Socket #0 OK 3 Win32_ComputerSystem CHBROSSO-WIN7VM 1 2
在 C++ 中运行 exe 和解析输出应该是最简单的部分。您还可以使用 POCO 库或 Boost.Process 来获得更简洁的代码。
(这是未经测试的代码)
//get wmic program output
FILE* pipe = _popen("wmic.exe cpu get", "r");
if (!pipe) throw std::exception("error");
char buffer[128];
std::string output;
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
output += buffer;
}
_pclose(pipe);
//split lines to a vector<string>
std::stringstream oss(output);
std::vector<std::string> processor_description; std::string buffer;
while (std::getline(oss, buffer))
processor_description.push_back(buffer);
//processor_description has n+1 elements, n being nb of sockets, +1 is the header of columns