Esempio n. 1
0
WinProcMon::~WinProcMon()
{
  if (mQuery != 0) {
    PdhCloseQuery(mQuery);
    mQuery = 0;
  }
}
void PerformanceManager::terminate()
{
	if (m_canAccessCPU)
	{
		PdhCloseQuery(m_queryHandle);
	}
}
Esempio n. 3
0
/* Must be called before the program exits, or to close all the capture items
 * before opening with a call to start_capture
 */
void sg_win32_end_capture()
{
#ifdef WIN32
	int i;
	PDH_STATUS pdh_status;

	if(!is_started) {
		return;
	}

	pdh_status = PdhCloseQuery(h_query);
	for (i=0; i < SG_WIN32_SIZE; ++i) {
		PdhRemoveCounter(current_han[i]);
		current_han[i] = NULL;
	}
	/*free_io(&diskio_no, diskio_names, diskio_rhan, diskio_whan);
	free_io(&netio_no, netio_names, netio_rhan, netio_shan);*/
	for (i=0; i < diskio_no; ++i) {
		PdhRemoveCounter(diskio_rhan[i]);
		PdhRemoveCounter(diskio_whan[i]);
		free(diskio_names[i]);
	}
	free(diskio_names);
	free(diskio_rhan);
	free(diskio_whan);
	diskio_no = 0;

	is_started = 0;
#endif
}
Esempio n. 4
0
SCTReturn SCTStatistics::Shutdown()
{
	if(mCanReadCpu)
		PdhCloseQuery(mQueryHandle);

	return OK;
}
Esempio n. 5
0
// Function name	: CPerfMon::Uninitialize
// Description	    : Closes the query and fress all memory
// Return type		: void
//
// R E V I S I O N S:
// DATE       PROGRAMMER      CHANGES
//
void CPerfMon::Uninitialize()
{
	PdhCloseQuery(&m_hQuery);

	// clean memory
	for (int i=0;i<m_aCounters.size();i++)
		delete m_aCounters[ i ];
}
Esempio n. 6
0
/******************************************************************************
 *                                                                            *
 * Comments: Get the value of a counter. If it is a rate counter,             *
 *           sleep 1 second to get the second raw value.                      *
 *                                                                            *
 ******************************************************************************/
PDH_STATUS	calculate_counter_value(const char *function, const char *counterpath, double *value)
{
    PDH_HQUERY		query;
    PDH_HCOUNTER		handle = NULL;
    PDH_STATUS		pdh_status;
    PDH_RAW_COUNTER		rawData, rawData2;
    PDH_FMT_COUNTERVALUE	counterValue;

    if (ERROR_SUCCESS != (pdh_status = zbx_PdhOpenQuery(function, &query)))
        return pdh_status;

    if (ERROR_SUCCESS != (pdh_status = zbx_PdhAddCounter(function, NULL, query, counterpath, &handle)))
        goto close_query;

    if (ERROR_SUCCESS != (pdh_status = zbx_PdhCollectQueryData(function, counterpath, query)))
        goto remove_counter;

    if (ERROR_SUCCESS != (pdh_status = zbx_PdhGetRawCounterValue(function, counterpath, handle, &rawData)))
        goto remove_counter;

    if (PDH_CSTATUS_INVALID_DATA == (pdh_status = PdhCalculateCounterFromRawValue(handle, PDH_FMT_DOUBLE |
                                     PDH_FMT_NOCAP100, &rawData, NULL, &counterValue)))
    {
        /* some (e.g., rate) counters require two raw values, MSDN lacks documentation */
        /* about what happens but tests show that PDH_CSTATUS_INVALID_DATA is returned */

        zbx_sleep(1);

        if (ERROR_SUCCESS == (pdh_status = zbx_PdhCollectQueryData(function, counterpath, query)) &&
                ERROR_SUCCESS == (pdh_status = zbx_PdhGetRawCounterValue(function, counterpath,
                                               handle, &rawData2)))
        {
            pdh_status = PdhCalculateCounterFromRawValue(handle, PDH_FMT_DOUBLE | PDH_FMT_NOCAP100,
                         &rawData2, &rawData, &counterValue);
        }
    }

    if (ERROR_SUCCESS != pdh_status || (PDH_CSTATUS_VALID_DATA != counterValue.CStatus &&
                                        PDH_CSTATUS_NEW_DATA != counterValue.CStatus))
    {
        if (ERROR_SUCCESS == pdh_status)
            pdh_status = counterValue.CStatus;

        zabbix_log(LOG_LEVEL_DEBUG, "%s(): cannot calculate counter value '%s': %s",
                   function, counterpath, strerror_from_module(pdh_status, L"PDH.DLL"));
    }
    else
    {
        *value = counterValue.doubleValue;
    }
remove_counter:
    PdhRemoveCounter(handle);
close_query:
    PdhCloseQuery(query);

    return pdh_status;
}
Esempio n. 7
0
// |----------------------------------------------------------------------------|
// |						       Shutdown										|
// |----------------------------------------------------------------------------|
void CpuClass::Shutdown()
{
	if(m_canReadCpu)
	{
		PdhCloseQuery(m_queryHandle);
	}

	return;
}
void InfoCPU::Shutdown()
{
	if (mcanReadCpu)
	{
		PdhCloseQuery(mqueryHandle);
	}

	return;
}
Esempio n. 9
0
// Function name	: CPerfMon::Uninitialize
// Description	    : Closes the query and fress all memory
// Return type		: void
//
// R E V I S I O N S:
// DATE       PROGRAMMER      CHANGES
//
void CPerfMon::Uninitialize()
{
	PdhCloseQuery(&m_hQuery);

	// clean memory
	for (int i=0;i<m_aCounters.GetSize();i++)
	{
		delete m_aCounters.GetAt(i);
	}
}
Esempio n. 10
0
CCPUInfo::~CCPUInfo()
{
#ifdef TARGET_POSIX
  if (m_fProcStat != NULL)
    fclose(m_fProcStat);

  if (m_fProcTemperature != NULL)
    fclose(m_fProcTemperature);

  if (m_fCPUFreq != NULL)
    fclose(m_fCPUFreq);
#elif defined(TARGET_WINDOWS)
  if (m_cpuQueryFreq)
    PdhCloseQuery(m_cpuQueryFreq);

  if (m_cpuQueryLoad)
    PdhCloseQuery(m_cpuQueryLoad);
#endif
}
static vm_status vm_sys_info_remove_cpu_data(struct VM_SYSINFO_CPULOAD *dbuf) {
  vm_status rtval = VM_NULL_PTR;
  if (dbuf != NULL) {
    if (dbuf[0].CpuLoadQuery != 0)
      PdhCloseQuery(dbuf[0].CpuLoadQuery);
    if (dbuf[0].cpudes != NULL)
      free(dbuf[0].cpudes);
    free(dbuf);
    }
  return rtval;
  }
Esempio n. 12
0
PerformanceCounter::~PerformanceCounter() {
  if (counter_ != NULL) {
    PdhRemoveCounter(counter_);
    counter_ = NULL;
  }

  if (query_ != NULL) {
    PdhCloseQuery(query_);
    query_ = NULL;
  }
}
DiskTimeMuninNodePlugin::~DiskTimeMuninNodePlugin()
{
  for (size_t i = 0; i < m_DiskTimeCounters.size(); i++) {
    // Close the counters
    PdhRemoveCounter(m_DiskTimeCounters[i]);
  }

  if (m_PerfQuery != NULL) {
    // Close the query
    PdhCloseQuery(&m_PerfQuery);
  }
}
Esempio n. 14
0
nsresult
WinProcMon::Init()
{
  PDH_HQUERY query;
  PDH_HCOUNTER counter;

  // Get a query handle to the Performance Data Helper
  PDH_STATUS status = PdhOpenQuery(
                        NULL,      // No log file name: use real-time source
                        0,         // zero out user data token: unsued
                        &query);

  if (status != ERROR_SUCCESS) {
    LOG(("PdhOpenQuery error = %X", status));
    return NS_ERROR_FAILURE;
  }

  // Add a pre-defined high performance counter to the query.
  // This one is for the total CPU usage.
  status = PdhAddCounter(query, TotalCounterPath, 0, &counter);

  if (status != ERROR_SUCCESS) {
    PdhCloseQuery(query);
    LOG(("PdhAddCounter (_Total) error = %X", status));
    return NS_ERROR_FAILURE;
  }

  // Need to make an initial query call to set up data capture.
  status = PdhCollectQueryData(query);

  if (status != ERROR_SUCCESS) {
    PdhCloseQuery(query);
    LOG(("PdhCollectQueryData (init) error = %X", status));
    return NS_ERROR_FAILURE;
  }

  mQuery = query;
  mCounter = counter;
  return NS_OK;
}
Esempio n. 15
0
    ~ProcessorCounter()
    {
        if( m_hQuery )
        {
            PdhCloseQuery( m_hQuery );
            m_hQuery = NULL;
        }

        if( m_szCounterPath )
        {
            delete [] m_szCounterPath;
        }
    }
Esempio n. 16
0
JNIEXPORT void JNICALL Java_org_krakenapps_winapi_PerformanceCounter_close(JNIEnv *env, jobject obj, jint queryHandle, jint counterHandle) {
	PDH_STATUS stat = 0;

	stat = PdhRemoveCounter((PDH_HCOUNTER)counterHandle);
	if(stat != ERROR_SUCCESS) {
		fprintf(stderr, "Error in PdhRemoveCounter: 0x%x\n", stat);
		return;
	}

	stat = PdhCloseQuery((PDH_HQUERY)queryHandle);
	if(stat != ERROR_SUCCESS)
		fprintf(stderr, "Error in PdhCloseQuery: 0x%x\n", stat);
}
Esempio n. 17
0
File: pdh.c Progetto: 40a/sigar
JNIEXPORT void SIGAR_JNI(win32_Pdh_pdhCloseQuery)
(JNIEnv *env, jclass cur, jlong query)
{
    HQUERY     h_query    = (HQUERY)query;
    PDH_STATUS status;

    // Close the query and the log file.
    status = PdhCloseQuery(h_query);

    if (status != ERROR_SUCCESS) {
        win32_throw_exception(env, get_error_message(status));
        return;
    }
}
Esempio n. 18
0
/* We do not fail on add_counter here, as some counters may not exist on all
 * hosts. The rest will work, and the missing/failed counters will die nicely
 * elsewhere */
static int add_all_monitors()
{
	int i;
	char tmp[512];

	add_counter(PDH_USER, &(current_han[SG_WIN32_PROC_USER]));
	add_counter(PDH_PRIV, &(current_han[SG_WIN32_PROC_PRIV]));
	add_counter(PDH_IDLE, &(current_han[SG_WIN32_PROC_IDLE]));
	add_counter(PDH_INTER, &(current_han[SG_WIN32_PROC_INT]));
	add_counter(PDH_MEM_CACHE, &(current_han[SG_WIN32_MEM_CACHE]));
	add_counter(PDH_UPTIME, &(current_han[SG_WIN32_UPTIME]));
	add_counter(PDH_PAGEIN, &(current_han[SG_WIN32_PAGEIN]));
	add_counter(PDH_PAGEOUT, &(current_han[SG_WIN32_PAGEOUT]));

	diskio_names = get_instance_list("PhysicalDisk", &diskio_no);
	if (diskio_names != NULL) {
		diskio_rhan = (HCOUNTER *)malloc(sizeof(HCOUNTER) * diskio_no);
		if (diskio_rhan == NULL) {
			PdhCloseQuery(h_query);
			return -1;
		}
		diskio_whan = (HCOUNTER *)malloc(sizeof(HCOUNTER) * diskio_no);
		if (diskio_whan == NULL) {
			PdhCloseQuery(h_query);
			free (diskio_rhan);
			return -1;
		}
		for (i = 0; i < diskio_no; i++) {
			snprintf(tmp, sizeof(tmp), PDH_DISKIOREAD, diskio_names[i]);
			add_counter(tmp, &diskio_rhan[i]);

			snprintf(tmp, sizeof(tmp), PDH_DISKIOWRITE, diskio_names[i]);
			add_counter(tmp, &diskio_whan[i]);
		}
	}
	return 0;
}
Esempio n. 19
0
/**
 * Populates the host_memory structure using data retrieved using
 * GlobalMemoryStatusEx function and the Memory performance counter
 * object.
 * Returns FALSE if call to GlobalMemoryStatusEx produces an error, TRUE otherwise.
 * Note that the Windows use of memory and classification of use does
 * not map cleanly to Linux terms.
 * Windows Resource Monitor reports cached as Standby+Modified this is not the
 * equivalent of Linux file system cache, however it could be viewed as
 * analagous memory usage, and it makes sense to retain some consistency with
 * Windows tools.
 * Windows Resource Monitor reports free memory as free and zero page list bytes,
 * this is used for free memory. There are no obvious equivalents for shared
 * and buffers so these counters are reported as unknown.
 * Windows also does not seem to report swapping (all memory associated with a process
 * swapped in/out of memory). Memory\\Pages Input/sec and Memory\\Pages Output/sec
 * are used for page_in and page_out.
 */
BOOL readMemoryCounters(SFLHost_mem_counters *mem) 
{
	MEMORYSTATUSEX memStat;
	memStat.dwLength = sizeof(memStat);
	if (GlobalMemoryStatusEx(&memStat) == 0){
		myLog(LOG_ERR,"GlobalMemoryStatusEx failed: %d\n",GetLastError());
		return FALSE;
	}
	mem->mem_total = memStat.ullTotalPhys;
	mem->swap_total = memStat.ullTotalPageFile;
	mem->swap_free = memStat.ullAvailPageFile;
	PDH_HQUERY query;
	if (PdhOpenQuery(NULL, 0, &query) == ERROR_SUCCESS) {
		PDH_HCOUNTER free, standbyCore, standbyNormal, standbyReserve, modified, pageIn, pageOut;
		if (addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_FREE, &query, &free) == ERROR_SUCCESS &&
			addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_STANDBY_CORE, &query, &standbyCore) == ERROR_SUCCESS &&
			addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_STANDBY_NORMAL, &query, &standbyNormal) == ERROR_SUCCESS &&
			addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_STANDBY_RESERVE, &query, &standbyReserve) == ERROR_SUCCESS &&
			addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_MODIFIED, &query, &modified) == ERROR_SUCCESS &&
			addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_PAGE_IN, &query, &pageIn) == ERROR_SUCCESS &&
			addCounterToQuery(MEM_COUNTER_OBJECT, NULL, MEM_COUNTER_PAGE_OUT, &query, &pageOut) == ERROR_SUCCESS &&
			PdhCollectQueryData(query) == ERROR_SUCCESS) {
			mem->mem_free = getRawCounterValue(&free);
			mem->mem_cached = getRawCounterValue(&standbyCore) +
				getRawCounterValue(&standbyNormal) +
				getRawCounterValue(&standbyReserve) +
				getRawCounterValue(&modified);
			mem->page_in = (uint32_t)getRawCounterValue(&pageIn);
			mem->page_out = (uint32_t)getRawCounterValue(&pageOut);
		}
		PdhCloseQuery(query);
	}

	//There are no obvious Windows equivalents
    mem->mem_shared = UNKNOWN_GAUGE_64;
	mem->mem_buffers = UNKNOWN_GAUGE_64;
	//using the definition that swapping is when all the memory associated with a
	//process is moved in/out of RAM
	mem->swap_in = UNKNOWN_COUNTER;
	mem->swap_out = UNKNOWN_COUNTER;
	myLog(LOG_INFO,
		"readMemoryCounters:\n\ttotal: \t\t%I64d\n\tfree: \t\t%I64d\n"
		"\tcached: \t%I64d\n\tpage_in: \t%d\n\tpage_out: \t%d\n"
		"\tswap_total: \t%I64d\n\tswap_free: \t%I64d\n",
		mem->mem_total, mem->mem_free,
		mem->mem_cached, mem->page_in, mem->page_out,
		mem->swap_total, mem->swap_free);
	return TRUE;
}
Esempio n. 20
0
void CSystemInfo::GetWinSystemInfo()
{
	HQUERY	hQuery = NULL ;
	char   szPathBuffer[MAX_PATH];

	if( PdhOpenQuery(NULL, NULL, &hQuery) != ERROR_SUCCESS )
		return ;

	ZeroMemory(szPathBuffer, sizeof(szPathBuffer));

	PDH_FMT_COUNTERVALUE  fmtValue;

	//CPU使用率
//	strcpy(szPathBuffer, "\\Processor(_Total)\\% Processor Time");
	strcpy(szPathBuffer, "\\Processor(0)\\% Processor Time");
	if( GetSysItemInfo(hQuery, szPathBuffer,  PDH_FMT_LONG, fmtValue) )
	{
		nCPU = fmtValue.longValue ;
	}

	//进程数
	strcpy(szPathBuffer, "\\System\\Processes");
	if( GetSysItemInfo(hQuery, szPathBuffer,  PDH_FMT_LONG, fmtValue) )
	{
		nProcessNumber = fmtValue.longValue;
	}

	//线程数
	strcpy(szPathBuffer, "\\System\\Threads");
	if( GetSysItemInfo(hQuery, szPathBuffer,  PDH_FMT_LONG, fmtValue) )
	{
		nThreadNumber =fmtValue.longValue;
	}

	strcpy(szPathBuffer, "\\Memory\\Commit Limit");
	if( GetSysItemInfo(hQuery, szPathBuffer,  PDH_FMT_LONG, fmtValue) )
	{
		nMemoryTotal =fmtValue.longValue;
	}

	strcpy(szPathBuffer, "\\Memory\\Committed Bytes");
	if( GetSysItemInfo(hQuery, szPathBuffer,  PDH_FMT_LONG, fmtValue) )
	{
		nUserMemory =fmtValue.longValue;
	}

	PdhCloseQuery(hQuery);
}
Esempio n. 21
0
double getCpuLoad(){
    PDH_HCOUNTER Counter;
	DWORD dwType;
	PDH_FMT_COUNTERVALUE Value;
	double ret = 0;
	PDH_HQUERY cpu_load_query = NULL;
	
	if(PdhOpenQuery(NULL, 0, &cpu_load_query) == ERROR_SUCCESS) {
		if(PdhAddCounter(cpu_load_query, "\\Processor(_Total)\\% Processor Time", 0, &Counter) == ERROR_SUCCESS &&
		PdhCollectQueryData(cpu_load_query) == ERROR_SUCCESS &&
		PdhGetFormattedCounterValue(Counter, PDH_FMT_DOUBLE, &dwType, &Value) == ERROR_SUCCESS) {
			ret = (Value.doubleValue * getCpuNum()) / 100.0;
		}
		if (cpu_load_query) PdhCloseQuery(cpu_load_query);
	}
	return ret;
}
Esempio n. 22
0
static
LONG
CloseAndDeleteLogEntry (
    IN  PLOG_INFO   pLog,
    IN  DWORD       dwFlags
)
{
    LONG  pdhStatus = ERROR_SUCCESS;

    // call any type-specific open functions
    switch (LOWORD(pLog->dwLogFormat)) {
        case OPD_CSV_FILE:
        case OPD_TSV_FILE:
            pdhStatus = CloseTextLog(pLog);
            break;

        default:
            pdhStatus = ERROR_NOT_SUPPORTED;
            break;
    }

    if (pdhStatus == ERROR_SUCCESS) {
        if (pLog->lpMappedFileBase != NULL) {
            UnmapViewOfFile (pLog->lpMappedFileBase);
        }

        if (pLog->hMappedLogFile != NULL) {
            CloseHandle (pLog->hMappedLogFile);
        }

        if (pLog->hLogFileHandle != INVALID_HANDLE_VALUE) {
            CloseHandle (pLog->hLogFileHandle);
        }

        if (pLog->hCatFileHandle != INVALID_HANDLE_VALUE) {

            CloseHandle (pLog->hCatFileHandle);
        }

        if ((dwFlags & FLAGS_CLOSE_QUERY) == FLAGS_CLOSE_QUERY) {
            pdhStatus = PdhCloseQuery (pLog->hQuery);
        }
    }

    return pdhStatus;
}
Esempio n. 23
0
uint64_t readSingleCounter(char* path)
{
    PDH_HQUERY Query = NULL;
    PDH_HCOUNTER Counter;
	DWORD dwType;
	PDH_RAW_COUNTER Value;
	LONGLONG ret = 0;

    if(PdhOpenQuery(NULL, 0, &Query) == ERROR_SUCCESS) {
		if(PdhAddCounter(Query, path, 0, &Counter) == ERROR_SUCCESS &&
		   PdhCollectQueryData(Query) == ERROR_SUCCESS &&
		   PdhGetRawCounterValue(Counter, &dwType, &Value) == ERROR_SUCCESS) {
			ret = Value.FirstValue;
		}
        if (Query) PdhCloseQuery(Query);
    }
	return (uint64_t)ret;
}
Esempio n. 24
0
uint64_t readFormattedCounter(char* path)
{
    PDH_HQUERY Query = NULL;
    PDH_HCOUNTER Counter;
	DWORD dwType;
	PDH_FMT_COUNTERVALUE Value;
	LONGLONG ret = 0;

    if(PdhOpenQuery(NULL, 0, &Query) == ERROR_SUCCESS) {
		if(PdhAddCounter(Query, path, 0, &Counter) == ERROR_SUCCESS && 
           PdhCollectQueryData(Query) == ERROR_SUCCESS &&
		   PdhGetFormattedCounterValue(Counter, PDH_FMT_LARGE, &dwType, &Value) == ERROR_SUCCESS) { 
			ret = Value.largeValue;
		}
		if (Query) PdhCloseQuery(Query);
    }
	return (uint64_t)ret;
}
Esempio n. 25
0
/**
 * @brief
 *      closes profile .
 *
 * @param[in] prof - pointer to PDH_profile struct
 *
 * @return      BOOL
 * @retval      TRUE    success
 * @retval      FALSE   error
 *
 */
static BOOL
close_profile(PDH_profile *prof)
{
	BOOL ret = TRUE;

	__try {
		if (prof->hQuery == NULL) {
			ret = FALSE;
		} else {
			if (PdhCloseQuery(prof->hQuery) != ERROR_SUCCESS) {
				prof->hQuery = NULL;
				ret = FALSE;
			}
		}
	}
	__except(EXCEPTION_EXECUTE_HANDLER) {
		ret = FALSE;
	}

	return (ret);
}
Esempio n. 26
0
uint32_t readMultiCounter(char* path, PPDH_RAW_COUNTER_ITEM *ppBuffer)
{
    PDH_HQUERY Query = NULL;
    PDH_HCOUNTER Counter;
	DWORD bufSize = 0, itemCount = 0;
	uint32_t ret = 0;

    if(PdhOpenQuery(NULL, 0, &Query) == ERROR_SUCCESS) {
		if(PdhAddCounter(Query, path, 0, &Counter) == ERROR_SUCCESS &&
		   PdhCollectQueryData(Query) == ERROR_SUCCESS &&
		   PdhGetRawCounterArray(Counter, &bufSize, &itemCount, NULL) == PDH_MORE_DATA) {
			*ppBuffer = (PPDH_RAW_COUNTER_ITEM)my_calloc(bufSize);
			if(PdhGetRawCounterArray(Counter, &bufSize, &itemCount, *ppBuffer) == ERROR_SUCCESS) {
				ret = itemCount;
				if(ret > 0 && strncmp("_Total",ppBuffer[0][itemCount-1].szName,6) == 0) {
					ret--; // use readSingleCounter if you need _Total;
				}
			}
		}
		if (Query) PdhCloseQuery(Query);
    }
	return (uint32_t)ret;
}
Esempio n. 27
0
void	free_perf_collector()
{
	PERF_COUNTER_DATA	*cptr;

	if (SUCCEED != perf_collector_started())
		return;

	for (cptr = ppsd.pPerfCounterList; cptr != NULL; cptr = cptr->next)
	{
		if (NULL != cptr->handle)
		{
			PdhRemoveCounter(cptr->handle);
			cptr->handle = NULL;
		}
	}

	PdhCloseQuery(ppsd.pdh_query);
	ppsd.pdh_query = NULL;

	free_perf_counter_list();

	zbx_mutex_destroy(&perfstat_access);
}
bool TSmartServer::GetMemoryInfo()
{
	HQUERY          hQuery;
	PDH_STATUS      pdhStatus;
	PDH_FMT_COUNTERVALUE  fmtValue;
	CHAR           szPathBuffer[MAX_PATH] = {'\0'};
	// Open the query object.
	pdhStatus = PdhOpenQuery (0, 0, &hQuery);
	if(pdhStatus!=ERROR_SUCCESS)
		return false;
	strcpy(szPathBuffer,"\\Memory\\Commit Limit"); 
	if(!GetSysItemInfo(hQuery, szPathBuffer, PDH_FMT_LONG,fmtValue))
		return false;
	nTotalMemory=fmtValue.longValue/1024;
	strcpy(szPathBuffer,"\\Memory\\Committed Bytes"); 
	if(!GetSysItemInfo(hQuery, szPathBuffer, PDH_FMT_LONG,fmtValue))
		return false;
	nUseMemory=fmtValue.longValue/1024;
	strcpy(szPathBuffer,"\\Memory\\Available Bytes"); 
	if(!GetSysItemInfo(hQuery, szPathBuffer, PDH_FMT_LONG,fmtValue))
		return false;
	nFreeMemory=fmtValue.longValue/1024;

	/*
\\Processor(_Total)\\% Processor Time CPU使用率
\\System\\Processes 当前系统进程数
\\System\\Threads 当前系统线程数
\\Memory\\Commit Limit 总共内存数K (包括虚拟内存)
\\Memory\\Committed Bytes 已用内存数K (包括虚拟内存)
\\TCP\\Connections Active 系统中已建立的 TCP连接个数
其它Object Items 可以利用PdhEnumObjects()和PdhEnumObjectItems()得到
反正我只要用到上面的东东:)
*/
	// Close the query.
	pdhStatus = PdhCloseQuery (hQuery);
	return true;
}
Esempio n. 29
0
void ZeroProcessMonitor::CloseCpuUsageCounter() {
	// CPU 사용량 카운터 제거
	PDH_STATUS pdhStatus = PdhCloseQuery(cpuUsageQuery);
}
Esempio n. 30
0
bool
GetPdhCounterValue(LPTSTR	pszInstanceName,	// インスタンス名
	LPTSTR	pszCounterName,		// カウンター名
	DWORD	dwFormat,			// 受け取る値の型の種類
	void*	pValue,				// 値受け取りバッファー
	DWORD	dwValueSize,		// 値受け取りバッファーのサイズ(byte)
	DWORD	dwSleepMilliSecond = 0)	// [in]値受け取り時にスリープをするか
{
	// 入力チェック
	if (NULL == pszInstanceName
		|| NULL == pszCounterName
		|| NULL == pValue
		|| 0 == dwValueSize)
	{
		//assert( !"入力エラー" );
		return false;
	}

	bool		bResult = false;		// 結果

	HQUERY		hQuery = NULL;		// 要求ハンドル
	HCOUNTER	hCounter = NULL;	// カウンターハンドル

									// カウンターパスの作成
	TCHAR szCounterPath[1024];
	if (1 != MakeCounterPath(pszInstanceName, pszCounterName, szCounterPath, 1024))
	{
		goto LABEL_END;
	}

	// 要求ハンドルの作成
	if (ERROR_SUCCESS != PdhOpenQuery(NULL,
		0,
		&hQuery))	// 要求ハンドル
	{
		goto LABEL_END;
	}

	// 作成したカウンターパスを要求ハンドルに登録。カウンターハンドルを得ておく。
	if (ERROR_SUCCESS != PdhAddCounter(hQuery,			// 要求ハンドル
		szCounterPath,
		0,
		&hCounter))	// カウンターハンドル
	{
		goto LABEL_END;
	}

	// 要求データの取得
	if (ERROR_SUCCESS != PdhCollectQueryData(hQuery))
	{
		goto LABEL_END;
	}
	if (0 < dwSleepMilliSecond)
	{
		Sleep(dwSleepMilliSecond);
		if (ERROR_SUCCESS != PdhCollectQueryData(hQuery))
		{
			goto LABEL_END;
		}
	}

LABEL_END:
	PDH_FMT_COUNTERVALUE	fmtValue;

	PdhGetFormattedCounterValue(hCounter, dwFormat, NULL, &fmtValue);

	bResult = true;

	PdhRemoveCounter(hCounter);
	PdhCloseQuery(hQuery);
	if (false == bResult)
	{	// 失敗
		//assert( !"失敗" );
		return false;
	}

	// 成功
	switch (dwFormat)
	{
	case PDH_FMT_LONG:
		if (dwValueSize != sizeof(LONG))
		{
			//assert( !"受け取る値の型の種類に対して値受け取りバッファーのサイズが不正" );
			return false;
		}
		else
		{
			LONG* plValue = (LONG*)pValue;
			*plValue = fmtValue.longValue;
		}
		break;
	case PDH_FMT_DOUBLE:
		if (dwValueSize != sizeof(double))
		{
			//assert( !"受け取る値の型の種類に対して値受け取りバッファーのサイズが不正" );
			return false;
		}
		else
		{
			double* pdValue = (double*)pValue;
			*pdValue = fmtValue.doubleValue;

		}
		break;
	case PDH_FMT_ANSI:
	case PDH_FMT_UNICODE:
	case PDH_FMT_LARGE:
	default:
		//assert( !"未対応" );
		return false;
	}
	return true;
}