I'm trying to read the system uptime using performance counters in C++. I want to support both XP and Windows 7 at minimum.
The following code works fine on Windows XP...
HQUERY hQuery; HCOUNTER hCounter;
PDH_FMT_COUNTERVALUE Value;
int ret = 0;
if (PdhOpenQuery(NULL, 0, &hQuery) == ERROR_SUCCESS) {
if ((status = PdhAddCounter(hQuery, queryURI, 0, &hCounter)) == ERROR_SUCCESS) {
if ((status = PdhCollectQueryData(hQuery)) == ERROR_SUCCESS) {
if ((status = PdhGetFormattedCounterValue(hCounter, PDH_FMT_LARGE, NULL, &Value)) == ERROR_SUCCESS) {
ret = (DWORD)(Value.largeValue);
}
}
PdhRemoveCounter(hCounte开发者_运维问答r);
}
PdhCloseQuery(hQuery);
}
return ret;
..but it fails on Windows 7. Specifically, PdhCollectQueryData returns PDH_NO_DATA regardless of whether or not i run as administrator.
How can i get the system uptime on both Windows 7 and XP? I expect the times to be much larger than the 49-day overflow of GetTickCount, and i would rather not have separate PDH versions for XP and GetTickCount64 versions for 7 if at all possible...
So the help for PdhCollectQueryData indicates that PDH_NO_DATA can be returned if the process doing the query lacks the appropriate elevated token to allow the query. See if you can check exactly what user permissions the process itself has been allocated, regardless of whether you are logged in as admin or not. Windows 7 has a lot of granularity to this concept, especially with UAC turned on. There can be a distinction also between the local Administrator account created with the OS & a member of the Administrators group in terms of what permissions the account ends up with, though I've not encountered a specific one on performance counters.
Try an explicit 'Run as administrator' on the process, for example, and ensure the administrator account you're using really does have that permission (I'm not sure from your question whether you have already tried this or not). Try a user account in the Performance Logs User Group. Try the account that was created when the OS was installed. Try with UAC off. These hopefully should help nail down the source of the problem.
From the Microsoft help on the subject:
Only the administrator of the computer or users in the Performance Logs User Group can log and view counter data. Users in the Administrator group can log and view counter data only if the tool they use to log and view counter data is started from a Command Prompt window that is opened with Run as administrator.... Users in the Performance Monitoring Users group can view counter data.
精彩评论