[C++] 檢測電腦服務(Windows Service)狀態

檢測電腦服務(Windows Service)狀態

 

參考MSDN上的程式做調整,檢查電腦目前Smart Card Service的服務狀態:

 


TCHAR szSvcName[] = _TEXT("SCardSvr");
SC_HANDLE schSCManager;
SC_HANDLE schService;

SERVICE_STATUS_PROCESS ssStatus; 
DWORD dwOldCheckPoint; 
DWORD dwStartTickCount;
DWORD dwWaitTime;
DWORD dwBytesNeeded;

// Get a handle to the SCM database. 

schSCManager = OpenSCManager( 
	NULL,                    // local computer
	NULL,                    // ServicesActive database 
	SC_MANAGER_ALL_ACCESS);  // full access rights 

if (NULL == schSCManager) 
{
	printf("OpenSCManager failed (%d)\n", GetLastError());

}

// Get a handle to the service.

schService = OpenService( 
	schSCManager,         // SCM database 
	szSvcName,            // name of service         
	SERVICE_QUERY_STATUS | 
	SERVICE_ENUMERATE_DEPENDENTS
	);  // full access 

if (schService == NULL)
{ 
	printf("OpenService failed (%d)\n", GetLastError()); 
	CloseServiceHandle(schSCManager);

}    

// Check the status in case the service is not stopped. 

if (!QueryServiceStatusEx( 
		schService,                     // handle to service 
		SC_STATUS_PROCESS_INFO,         // information level
		(LPBYTE) &ssStatus,             // address of structure
		sizeof(SERVICE_STATUS_PROCESS), // size of structure
		&dwBytesNeeded ) )              // size needed if buffer is too small
{
	printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
	CloseServiceHandle(schService); 
	CloseServiceHandle(schSCManager);

}
else
{
	// Check if the service is already running. It would be possible 
	// to stop the service here, but for simplicity this example just returns. 
	printf("Service status: ");
	switch(ssStatus.dwCurrentState)
	{
		case SERVICE_STOPPED:
		case SERVICE_STOP_PENDING:
			printf("Stop");
			break;
		case SERVICE_PAUSED:
		case SERVICE_PAUSE_PENDING:
			printf("Pause");
			break;
		case SERVICE_CONTINUE_PENDING:
		case SERVICE_RUNNING:
		case SERVICE_START_PENDING:
			printf("Running");
			break;
	} 
	cout << endl;
}

 

相關連結:

SvcControl.cpp

 

Dotblogs 的標籤: ,