本文整理汇总了C++中CloseServiceHandle函数的典型用法代码示例。如果您正苦于以下问题:C++ CloseServiceHandle函数的具体用法?C++ CloseServiceHandle怎么用?C++ CloseServiceHandle使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了CloseServiceHandle函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: EncServiceInstall
INT EncServiceInstall()
{
SC_HANDLE hSCManager = NULL;
SC_HANDLE hService = NULL;
SERVICE_DESCRIPTION ServiceDescription;
SERVICE_PRESHUTDOWN_INFO ServicePreshutdownInfo;
CHAR BinaryPath[MAX_PATH + 64];
INT Ret = -1;
if(!GetBinaryPath(BinaryPath, sizeof(BinaryPath))) {
PrintLastError("EncServiceInstall:");
goto err;
}
hSCManager = OpenSCManager(
NULL,
SERVICES_ACTIVE_DATABASE,
SC_MANAGER_ALL_ACCESS
);
if(NULL == hSCManager) {
PrintLastError("EncServiceInstall:");
goto err;
}
hService = CreateService(
hSCManager,
ENC_MON_SERVICE_NAME,
ENC_MON_SERVICE_DISPLAY_NAME,
SC_MANAGER_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
BinaryPath,
NULL,
NULL,
ENC_DISK_SERVICE_NAME,
NULL,
NULL
);
if(NULL == hService) {
PrintLastError("EncServiceInstall:");
goto err;
}
ServiceDescription.lpDescription = ENC_MON_SERVICE_DESCRIPTION;
if(!ChangeServiceConfig2(
hService,
SERVICE_CONFIG_DESCRIPTION,
&ServiceDescription
)) {
PrintLastError("EncServiceInstall:");
goto err;
}
ServicePreshutdownInfo.dwPreshutdownTimeout = ENC_MON_SERVICE_MAX_WAIT_MS;
if(!ChangeServiceConfig2(
hService,
SERVICE_CONFIG_PRESHUTDOWN_INFO,
&ServicePreshutdownInfo
)) {
PrintLastError("EncServiceInstall:");
goto err;
}
Ret = 0;
err:
if(NULL != hService) {
CloseServiceHandle(hService);
hService = NULL;
}
if(NULL != hSCManager) {
CloseServiceHandle(hSCManager);
hSCManager = NULL;
}
return Ret;
}
示例2: StopDependentServices
BOOL StopDependentServices(SC_HANDLE hSCManager, SC_HANDLE hService)
{
LPENUM_SERVICE_STATUS lpDependencies = NULL;
ENUM_SERVICE_STATUS ess;
SC_HANDLE hDepService;
SERVICE_STATUS_PROCESS ssp;
DWORD i, dwBytesNeeded, dwCount;
DWORD dwStartTime = GetTickCount();
DWORD dwTimeout = 30000; // 30 секундна пауза
// Пускане на буфер с нулева дължина, за да се получи желания размер на буфера.
if (EnumDependentServices(hService, SERVICE_ACTIVE, lpDependencies, 0, &dwBytesNeeded, &dwCount))
// Ако извикването на Enum-а е успешно, тогава няма зависими
// сервиси, така че не се прави нищо.
return TRUE;
if (GetLastError() != ERROR_MORE_DATA)
return FALSE; // Неочаквана грешка
// Алокиране на буфер за зависимостите.
lpDependencies = (LPENUM_SERVICE_STATUS)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesNeeded);
if (!lpDependencies)
return FALSE;
__try {
// Избройват се зависимостите.
if (!EnumDependentServices(hService, SERVICE_ACTIVE, lpDependencies,
dwBytesNeeded, &dwBytesNeeded, &dwCount))
return FALSE;
for (i=0; i<dwCount; i++) {
ess = *(lpDependencies + i);
// Отваря се сервиса
hDepService = OpenService(hSCManager, ess.lpServiceName, SERVICE_STOP|SERVICE_QUERY_STATUS);
if (!hDepService)
return FALSE;
__try {
// Изпраща се стоп код.
if (!ControlService(hDepService, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS)&ssp))
return FALSE;
// Изчаква се сервиса да спре.
while (ssp.dwCurrentState != SERVICE_STOPPED) {
Sleep(ssp.dwWaitHint);
if (!QueryServiceStatusEx(hDepService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded))
return FALSE;
if (ssp.dwCurrentState == SERVICE_STOPPED)
break;
if (GetTickCount() - dwStartTime > dwTimeout)
return FALSE;
}
} __finally {
// Винаги се изпуска дръжката на сервиса.
CloseServiceHandle(hDepService);
}
}
} __finally {
// Винаги се освобождава изброения буфер.
HeapFree(GetProcessHeap(), 0, lpDependencies);
}
return TRUE;
}
示例3: service_stop
NOEXPORT int service_stop(void) {
SC_HANDLE scm, service;
SERVICE_STATUS serviceStatus;
scm=OpenSCManager(0, 0, SC_MANAGER_CONNECT);
if(!scm) {
error_box(TEXT("OpenSCManager"));
return 1;
}
service=OpenService(scm, SERVICE_NAME, SERVICE_QUERY_STATUS|SERVICE_STOP);
if(!service) {
error_box(TEXT("OpenService"));
CloseServiceHandle(scm);
return 1;
}
if(!QueryServiceStatus(service, &serviceStatus)) {
error_box(TEXT("QueryServiceStatus"));
CloseServiceHandle(service);
CloseServiceHandle(scm);
return 1;
}
if(serviceStatus.dwCurrentState==SERVICE_STOPPED) {
message_box(TEXT("The service is already stopped"), MB_ICONERROR);
CloseServiceHandle(service);
CloseServiceHandle(scm);
return 1;
}
if(!ControlService(service, SERVICE_CONTROL_STOP, &serviceStatus)) {
error_box(TEXT("ControlService"));
CloseServiceHandle(service);
CloseServiceHandle(scm);
return 1;
}
do {
Sleep(1000);
if(!QueryServiceStatus(service, &serviceStatus)) {
error_box(TEXT("QueryServiceStatus"));
CloseServiceHandle(service);
CloseServiceHandle(scm);
return 1;
}
} while(serviceStatus.dwCurrentState!=SERVICE_STOPPED);
message_box(TEXT("Service stopped"), MB_ICONINFORMATION);
CloseServiceHandle(service);
CloseServiceHandle(scm);
return 0;
}
示例4: ServiceRun
BOOL ServiceRun()
{
SC_HANDLE scm, Service;
SERVICE_STATUS ssStatus;
DWORD dwOldCheckPoint;
DWORD dwStartTickCount;
DWORD dwWaitTime;
DWORD dwStatus;
scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (!scm) {
ErrorHandler("OpenSCManager", GetLastError());
}
Service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS);
if (!Service) {
ErrorHandler("OpenService", GetLastError());
return FALSE;
} else {
StartService(Service, 0, NULL);
srvc.GetStatus(Service);
if (!QueryServiceStatus( Service, &ssStatus) ) {
ErrorHandler("QueryServiceStatus", GetLastError());
}
dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
while (ssStatus.dwCurrentState == SERVICE_START_PENDING) {
dwWaitTime = ssStatus.dwWaitHint / 10;
if( dwWaitTime < 1000 ) {
dwWaitTime = 1000;
} else if ( dwWaitTime > 10000 ) {
dwWaitTime = 10000;
}
Sleep( dwWaitTime );
if (!QueryServiceStatus(Service, &ssStatus) ) {
break;
}
if ( ssStatus.dwCheckPoint > dwOldCheckPoint ) {
dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
} else {
if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint) {
break;
}
}
}
if (ssStatus.dwCurrentState == SERVICE_RUNNING) {
srvc.GetStatus(Service);
dwStatus = NO_ERROR;
} else {
printf("\nService not started.\n");
printf(" Current State: %d\n", ssStatus.dwCurrentState);
printf(" Exit Code: %d\n", ssStatus.dwWin32ExitCode);
printf(" Service Specific Exit Code: %d\n", ssStatus.dwServiceSpecificExitCode);
printf(" Check Point: %d\n", ssStatus.dwCheckPoint);
printf(" Wait Hint: %d\n", ssStatus.dwWaitHint);
dwStatus = GetLastError();
}
}
CloseServiceHandle(scm);
CloseServiceHandle(Service);
return TRUE;
}
示例5: WaitForServiceStop
/**
* Waits for a service to enter a stopped state.
* This function does not stop the service, it just blocks until the service
* is stopped.
*
* @param serviceName The service to wait for.
* @param maxWaitSeconds The maximum number of seconds to wait
* @return state of the service after a timeout or when stopped.
* A value of 255 is returned for an error. Typical values are:
* SERVICE_STOPPED 0x00000001
* SERVICE_START_PENDING 0x00000002
* SERVICE_STOP_PENDING 0x00000003
* SERVICE_RUNNING 0x00000004
* SERVICE_CONTINUE_PENDING 0x00000005
* SERVICE_PAUSE_PENDING 0x00000006
* SERVICE_PAUSED 0x00000007
* last status not set 0x000000CF
* Could no query status 0x000000DF
* Could not open service, access denied 0x000000EB
* Could not open service, invalid handle 0x000000EC
* Could not open service, invalid name 0x000000ED
* Could not open service, does not exist 0x000000EE
* Could not open service, other error 0x000000EF
* Could not open SCM, access denied 0x000000FD
* Could not open SCM, database does not exist 0x000000FE;
* Could not open SCM, other error 0x000000FF;
* Note: The strange choice of error codes above SERVICE_PAUSED are chosen
* in case Windows comes out with other service stats higher than 7, they
* would likely call it 8 and above. JS code that uses this in TestAUSHelper
* only handles values up to 255 so that's why we don't use GetLastError
* directly.
*/
DWORD
WaitForServiceStop(LPCWSTR serviceName, DWORD maxWaitSeconds)
{
// 0x000000CF is defined above to be not set
DWORD lastServiceState = 0x000000CF;
// Get a handle to the SCM database.
SC_HANDLE serviceManager = OpenSCManager(nullptr, nullptr,
SC_MANAGER_CONNECT |
SC_MANAGER_ENUMERATE_SERVICE);
if (!serviceManager) {
DWORD lastError = GetLastError();
switch(lastError) {
case ERROR_ACCESS_DENIED:
return 0x000000FD;
case ERROR_DATABASE_DOES_NOT_EXIST:
return 0x000000FE;
default:
return 0x000000FF;
}
}
// Get a handle to the service.
SC_HANDLE service = OpenServiceW(serviceManager,
serviceName,
SERVICE_QUERY_STATUS);
if (!service) {
DWORD lastError = GetLastError();
CloseServiceHandle(serviceManager);
switch(lastError) {
case ERROR_ACCESS_DENIED:
return 0x000000EB;
case ERROR_INVALID_HANDLE:
return 0x000000EC;
case ERROR_INVALID_NAME:
return 0x000000ED;
case ERROR_SERVICE_DOES_NOT_EXIST:
return 0x000000EE;
default:
return 0x000000EF;
}
}
DWORD currentWaitMS = 0;
SERVICE_STATUS_PROCESS ssp;
ssp.dwCurrentState = lastServiceState;
while (currentWaitMS < maxWaitSeconds * 1000) {
DWORD bytesNeeded;
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS), &bytesNeeded)) {
DWORD lastError = GetLastError();
switch (lastError) {
case ERROR_INVALID_HANDLE:
ssp.dwCurrentState = 0x000000D9;
break;
case ERROR_ACCESS_DENIED:
ssp.dwCurrentState = 0x000000DA;
break;
case ERROR_INSUFFICIENT_BUFFER:
ssp.dwCurrentState = 0x000000DB;
break;
case ERROR_INVALID_PARAMETER:
ssp.dwCurrentState = 0x000000DC;
break;
case ERROR_INVALID_LEVEL:
ssp.dwCurrentState = 0x000000DD;
break;
case ERROR_SHUTDOWN_IN_PROGRESS:
//.........这里部分代码省略.........
示例6: main
int main(int argc, char *argv[])
{
if(argc<6)
{
printf("Insufficient arguments: Service u/i ServiceName ServicePath DisplayName m/a [DependOnServiceName]\n");
return 1;
}
SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
SC_HANDLE hService;
if(hSCM == NULL)
{
printf("Could not open Service Control Manager. Aborting.\n");
return 1;
}
char *depend = NULL;
if (argc >= 7)
{
int slen = strlen(argv[6]);
int len = slen + 10;
depend = (char *) malloc(len);
memset(depend, 0, len);
strcpy(depend, argv[6]);
printf("Service depend on %s\n", depend);
}
if(*argv[1]!='u' && *argv[1]!='U')
{
if (argv[5][0] == 'm')
{
printf("installing on demand start service\n");
hService = CreateService(hSCM, argv[2],_T(argv[4]),SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_IGNORE,
argv[3],
NULL,NULL, depend,
NULL,
NULL );
}
else
{
printf("installing autostart service\n");
hService = CreateService(hSCM, argv[2],
_T(argv[4]),
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_IGNORE,
argv[3],
NULL,NULL, depend,
NULL,
NULL );
}
if (hService == NULL)
{
printf("Create Service failed (%d)\n", GetLastError() );
CloseServiceHandle(hSCM);
}
}
else
{
hService = OpenService( hSCM, argv[2], DELETE);
if(hService!=NULL)
DeleteService( hService );
}
CloseServiceHandle(hService);
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return 0;
}
示例7: Main_DlgProc
//.........这里部分代码省略.........
case WM_TIMER:
Main_OnRemindTimer();
break;
case WM_NOTIFY:
switch (((NMHDR*)lp)->code)
{
case TCN_SELCHANGE:
Main_OnSelectTab();
break;
}
break;
case WM_TRAYICON:
switch (lp)
{
case WM_LBUTTONDOWN:
if (IsServiceRunning() || !IsServiceConfigured())
Main_Show (TRUE);
else if (!g.fIsWinNT)
Message (MB_ICONHAND, IDS_UNCONFIG_TITLE_95, IDS_UNCONFIG_DESC_95);
else
ShowStartupWizard();
break;
case WM_RBUTTONDOWN:
HMENU hm;
if ((hm = TaLocale_LoadMenu (MENU_TRAYICON)) != 0)
{
POINT pt;
GetCursorPos(&pt);
HMENU hmDummy = CreateMenu();
InsertMenu (hmDummy, 0, MF_POPUP, (UINT)hm, NULL);
BOOL fRemind = FALSE;
lock_ObtainMutex(&g.credsLock);
for (size_t iCreds = 0; iCreds < g.cCreds; ++iCreds)
{
if (g.aCreds[ iCreds ].fRemind)
fRemind = TRUE;
}
lock_ReleaseMutex(&g.credsLock);
CheckMenuItem (hm, M_REMIND, MF_BYCOMMAND | ((fRemind) ? MF_CHECKED : MF_UNCHECKED));
SetForegroundWindow(hDlg);
TrackPopupMenu (GetSubMenu (hmDummy, 0),
TPM_RIGHTALIGN | TPM_RIGHTBUTTON,
pt.x, pt.y, NULL, hDlg, NULL);
PostMessage(hDlg, WM_NULL, 0, 0);
DestroyMenu (hmDummy);
}
break;
case WM_MOUSEMOVE:
Main_OnMouseOver();
break;
}
break;
case WM_OBTAIN_TOKENS:
if ( InterlockedIncrement (&g.fShowingMessage) != 1 )
InterlockedDecrement (&g.fShowingMessage);
else
ShowObtainCreds (wp, (char *)lp);
GlobalFree((void *)lp);
break;
case WM_START_SERVICE:
{
SC_HANDLE hManager;
if ((hManager = OpenSCManager ( NULL, NULL,
SC_MANAGER_CONNECT |
SC_MANAGER_ENUMERATE_SERVICE |
SC_MANAGER_QUERY_LOCK_STATUS)) != NULL)
{
SC_HANDLE hService;
if ((hService = OpenService ( hManager, TEXT("TransarcAFSDaemon"),
SERVICE_QUERY_STATUS | SERVICE_START)) != NULL)
{
if (StartService (hService, 0, 0))
TestAndDoMapShare(SERVICE_START_PENDING);
if ( KFW_is_available() && KFW_AFS_wait_for_service_start() ) {
#ifdef USE_MS2MIT
KFW_import_windows_lsa();
#endif /* USE_MS2MIT */
KFW_AFS_renew_tokens_for_all_cells();
}
CloseServiceHandle (hService);
}
CloseServiceHandle (hManager);
}
if (KFW_AFS_wait_for_service_start())
ObtainTokensFromUserIfNeeded(g.hMain);
}
break;
}
return FALSE;
}
示例8: nx_win32_svc_stop
static void nx_win32_svc_stop()
{
SC_HANDLE service_manager = NULL;
SC_HANDLE service_handle = NULL;
SERVICE_STATUS status;
nx_exception_t e;
// Connect to service manager
service_manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if ( service_manager == NULL )
{
nx_win32_error("Cannot initialize access to the service manager");
}
try
{
service_handle = OpenService(service_manager, "nxlog", SERVICE_ALL_ACCESS);
if ( service_handle == NULL )
{
nx_win32_error("Couldn't open nxlog service");
}
else
{
if ( QueryServiceStatus(service_handle, &status) )
{
if ( status.dwCurrentState != SERVICE_STOPPED )
{
log_info("Service currenty active - stopping service...");
if ( !ControlService(service_handle, SERVICE_CONTROL_STOP, &status) )
{
nx_win32_error("Couldn't stop service");
}
else
{
Sleep(500);
}
}
else
{
log_error("Service is already stopped");
}
}
// Close connection to service
CloseServiceHandle(service_handle);
}
// Close connection to service manager
CloseServiceHandle(service_manager);
}
catch(e)
{
if ( service_handle != NULL )
{
CloseServiceHandle(service_handle);
}
if ( service_manager != NULL )
{
CloseServiceHandle(service_manager);
}
rethrow(e);
}
}
示例9: VBoxServiceWinInstall
/**
* Installs the service.
*/
RTEXITCODE VBoxServiceWinInstall(void)
{
VBoxServiceVerbose(1, "Installing service ...\n");
TCHAR imagePath[MAX_PATH] = { 0 };
GetModuleFileName(NULL, imagePath, sizeof(imagePath));
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCManager == NULL)
{
VBoxServiceError("Could not open SCM! Error: %ld\n", GetLastError());
return RTEXITCODE_FAILURE;
}
RTEXITCODE rc = RTEXITCODE_SUCCESS;
SC_HANDLE hService = CreateService(hSCManager,
VBOXSERVICE_NAME, VBOXSERVICE_FRIENDLY_NAME,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
imagePath, NULL, NULL, NULL, NULL, NULL);
if (hService != NULL)
VBoxServiceVerbose(0, "Service successfully installed!\n");
else
{
DWORD dwErr = GetLastError();
switch (dwErr)
{
case ERROR_SERVICE_EXISTS:
VBoxServiceVerbose(1, "Service already exists, just updating the service config.\n");
hService = OpenService(hSCManager, VBOXSERVICE_NAME, SERVICE_ALL_ACCESS);
if (hService)
{
if (ChangeServiceConfig (hService,
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
imagePath,
NULL,
NULL,
NULL,
NULL,
NULL,
VBOXSERVICE_FRIENDLY_NAME))
VBoxServiceVerbose(1, "The service config has been successfully updated.\n");
else
rc = VBoxServiceError("Could not change service config! Error: %ld\n", GetLastError());
}
else
rc = VBoxServiceError("Could not open service! Error: %ld\n", GetLastError());
break;
default:
rc = VBoxServiceError("Could not create service! Error: %ld\n", dwErr);
break;
}
}
if (rc == RTEXITCODE_SUCCESS)
rc = vboxServiceWinSetDesc(hService);
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
return rc;
}
示例10: uninstall_driver
int WinPmem::install_driver() {
SC_HANDLE scm, service;
int status = -1;
// Try to load the driver from the resource section.
if (extract_driver() < 0)
goto error;
uninstall_driver();
scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (!scm) {
dprintf("[WINPMEM] Can not open SCM. Are you administrator?\n");
goto error;
}
service = CreateService(scm,
service_name,
service_name,
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
driver_filename_,
NULL,
NULL,
NULL,
NULL,
NULL);
if (GetLastError() == ERROR_SERVICE_EXISTS) {
service = OpenService(scm, service_name, SERVICE_ALL_ACCESS);
}
if (!service) {
goto error;
};
if (!StartService(service, 0, NULL)) {
if (GetLastError() != ERROR_SERVICE_ALREADY_RUNNING) {
dprintf("[WINPMEM] Error: StartService(), Cannot start the driver.\n");
goto service_error;
}
}
dprintf("[WINPMEM] Loaded Driver %s.\n", driver_filename_);
fd_ = CreateFile(TEXT("\\\\.\\") TEXT(PMEM_DEVICE_NAME),
// Write is needed for IOCTL.
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (fd_ == INVALID_HANDLE_VALUE) {
dprintf("[WINPMEM] Can not open raw device.");
status = -1;
};
status = 1;
service_error:
CloseServiceHandle(service);
CloseServiceHandle(scm);
error:
// Only remove the driver file if it was a temporary file.
if (driver_is_tempfile_) {
dprintf("[WINPMEM] Deleting %S", driver_filename_);
DeleteFile(driver_filename_);
};
return status;
}
示例11: nx_win32_svc_uninstall
static void nx_win32_svc_uninstall()
{
SC_HANDLE service_manager = NULL;
SC_HANDLE service_handle = NULL;
SERVICE_STATUS query_status;
nx_exception_t e;
// Connect to service manager
service_manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if ( service_manager == NULL )
{
nx_win32_error("Cannot initialize access to the service manager");
}
try
{
// Connect to service
service_handle = OpenService(service_manager, "nxlog", SERVICE_ALL_ACCESS | DELETE);
if ( service_handle == NULL )
{
nx_win32_error("Couldn't open nxlog service");
}
else
{
// Check that the service is stopped
if ( QueryServiceStatus(service_handle, &query_status) &&
(query_status.dwCurrentState == SERVICE_RUNNING) )
{
throw_msg("Service is running, please stop it first.");
}
else
{ // we can remove
if ( DeleteService(service_handle) == FALSE )
{
nx_win32_error("Couldn't delete service");
}
else
{
log_info("Service successfully uninstalled");
}
}
// Close connection to service
CloseServiceHandle(service_handle);
}
// Close connection to service manager
CloseServiceHandle(service_manager);
}
catch(e)
{
if ( service_handle != NULL )
{
CloseServiceHandle(service_handle);
}
if ( service_manager != NULL )
{
CloseServiceHandle(service_manager);
}
rethrow(e);
}
}
示例12: LoadDriver
//.........这里部分代码省略.........
SYSTEM_INFO SystemInfo;
//
// Prepend architecture-specific directory.
//
CfixklGetNativeSystemInfo( &SystemInfo );
switch ( SystemInfo.wProcessorArchitecture )
{
case PROCESSOR_ARCHITECTURE_INTEL:
TEST( SUCCEEDED( StringCchPrintf(
DriverPath,
_countof( DriverPath ),
L"..\\i386\\%s",
DriverFileName ) ) );
break;
case PROCESSOR_ARCHITECTURE_AMD64:
TEST( SUCCEEDED( StringCchPrintf(
DriverPath,
_countof( DriverPath ),
L"..\\amd64\\%s",
DriverFileName ) ) );
break;
default:
CFIX_ASSERT( !"Unsupported processor architecture" );
return ERROR_FUNCTION_FAILED;
}
ScMgr = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );
CFIX_ASSUME( ScMgr != NULL );
TEST( GetFullPathName( DriverPath, _countof( FullPath ), FullPath, &FilePart ) );
// CFIX_LOG( L"Attempting to load %s", FullPath );
//
// Windows 2000 may require a pause here.
//
Sleep( 1000 );
Service = CreateService(
ScMgr,
Name,
Name,
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
FullPath,
NULL,
NULL,
NULL,
NULL,
NULL );
TEST( Service || GetLastError() == ERROR_SERVICE_EXISTS );
if ( ERROR_SUCCESS == GetLastError() )
{
// Fine.
}
else if ( GetLastError() == ERROR_SERVICE_EXISTS )
{
//
// Windows 2000 may require a pause here.
//
Sleep( 1000 );
Service = OpenService( ScMgr, Name, SERVICE_ALL_ACCESS );
TEST( Service );
}
else
{
TEST( !"Unexpected SCM failure" );
}
//
// Windows 2000 may require a pause here.
//
Sleep( 1000 );
if ( ! StartService( Service, 0, NULL ) )
{
RetVal = GetLastError();
}
else
{
RetVal = ERROR_SUCCESS;
}
TEST( CloseServiceHandle( ScMgr ) );
TEST( CloseServiceHandle( Service ) );
//
// Windows 2000 may require a pause here.
//
Sleep( 1000 );
return RetVal;
}
示例13: lutil_srv_install
int lutil_srv_install(LPCTSTR lpszServiceName, LPCTSTR lpszDisplayName,
LPCTSTR lpszBinaryPathName, int auto_start)
{
HKEY hKey;
DWORD dwValue, dwDisposition;
SC_HANDLE schSCManager, schService;
char *sp = strchr( lpszBinaryPathName, ' ');
if ( sp ) *sp = '\0';
fprintf( stderr, "The install path is %s.\n", lpszBinaryPathName );
if ( sp ) *sp = ' ';
if ((schSCManager = OpenSCManager( NULL, NULL, SC_MANAGER_CONNECT|SC_MANAGER_CREATE_SERVICE ) ) != NULL )
{
if ((schService = CreateService(
schSCManager,
lpszServiceName,
lpszDisplayName,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
auto_start ? SERVICE_AUTO_START : SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
lpszBinaryPathName,
NULL, NULL, NULL, NULL, NULL)) != NULL)
{
char regpath[132];
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
snprintf( regpath, sizeof regpath,
"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\%s",
lpszServiceName );
/* Create the registry key for event logging to the Windows NT event log. */
if ( RegCreateKeyEx(HKEY_LOCAL_MACHINE,
regpath, 0,
"REG_SZ", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey,
&dwDisposition) != ERROR_SUCCESS)
{
fprintf( stderr, "RegCreateKeyEx() failed. GetLastError=%lu (%s)\n", GetLastError(), GetLastErrorString() );
RegCloseKey(hKey);
return(0);
}
if ( sp ) *sp = '\0';
if ( RegSetValueEx(hKey, "EventMessageFile", 0, REG_EXPAND_SZ, lpszBinaryPathName, strlen(lpszBinaryPathName) + 1) != ERROR_SUCCESS)
{
fprintf( stderr, "RegSetValueEx(EventMessageFile) failed. GetLastError=%lu (%s)\n", GetLastError(), GetLastErrorString() );
RegCloseKey(hKey);
return(0);
}
dwValue = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE;
if ( RegSetValueEx(hKey, "TypesSupported", 0, REG_DWORD, (LPBYTE) &dwValue, sizeof(DWORD)) != ERROR_SUCCESS)
{
fprintf( stderr, "RegCreateKeyEx(TypesSupported) failed. GetLastError=%lu (%s)\n", GetLastError(), GetLastErrorString() );
RegCloseKey(hKey);
return(0);
}
RegCloseKey(hKey);
return(1);
}
else
{
fprintf( stderr, "CreateService() failed. GetLastError=%lu (%s)\n", GetLastError(), GetLastErrorString() );
CloseServiceHandle(schSCManager);
return(0);
}
}
else
fprintf( stderr, "OpenSCManager() failed. GetLastError=%lu (%s)\n", GetLastError(), GetLastErrorString() );
return(0);
}
示例14: ACE_TEXT
int
ACE_NT_Service::insert (DWORD start_type,
DWORD error_control,
const ACE_TCHAR *exe_path,
const ACE_TCHAR *group_name,
LPDWORD tag_id,
const ACE_TCHAR *dependencies,
const ACE_TCHAR *account_name,
const ACE_TCHAR *password,
DWORD desired_access)
{
ACE_TCHAR this_exe[MAXPATHLEN + 2];
// Insure ACE_OS::last_error finds GetLastError unless we set errno.
errno = 0;
if (exe_path == 0)
{
if (ACE_TEXT_GetModuleFileName (0, this_exe + 1, MAXPATHLEN) == 0)
return -1;
// Make sure that this_exe is quoted
this_exe[0] = ACE_TEXT ('\"');
ACE_OS::strcat (this_exe, ACE_TEXT ("\""));
exe_path = this_exe;
}
SC_HANDLE sc_mgr = ACE_TEXT_OpenSCManager (this->host (),
0,
SC_MANAGER_ALL_ACCESS);
if (sc_mgr == 0)
return -1;
SC_HANDLE sh = ACE_TEXT_CreateService (sc_mgr,
this->name (),
this->desc (),
desired_access,
this->svc_status_.dwServiceType,
start_type,
error_control,
exe_path,
group_name,
tag_id,
dependencies,
account_name,
password);
// If there was an error, stash GetLastError before CloseServiceHandle
// smashes it. ACE_OS::last_error will find the saved error value.
if (sh == 0)
ACE_OS::set_errno_to_last_error ();
CloseServiceHandle (sc_mgr);
if (sh == 0)
return -1;
if (this->svc_sc_handle_ != 0)
CloseServiceHandle (this->svc_sc_handle_);
this->svc_sc_handle_ = sh;
return 0;
}
示例15: WinDivertDriverInstall
/*
* Install the WinDivert driver.
*/
static SC_HANDLE WinDivertDriverInstall(VOID)
{
DWORD err, retries = 2;
SC_HANDLE manager = NULL, service = NULL;
wchar_t windivert_sys[MAX_PATH+1];
SERVICE_STATUS status;
// Open the service manager:
manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (manager == NULL)
{
goto WinDivertDriverInstallExit;
}
// Check if the WinDivert service already exists; if so, start it.
WinDivertDriverInstallReTry:
service = OpenService(manager, WINDIVERT_DEVICE_NAME, SERVICE_ALL_ACCESS);
if (service != NULL)
{
goto WinDivertDriverInstallExit;
}
// Get driver file:
if (!WinDivertGetDriverFileName(windivert_sys))
{
goto WinDivertDriverInstallExit;
}
// Create the service:
service = CreateService(manager, WINDIVERT_DEVICE_NAME,
WINDIVERT_DEVICE_NAME, SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, windivert_sys, NULL, NULL,
NULL, NULL, NULL);
if (service == NULL)
{
if (GetLastError() == ERROR_SERVICE_EXISTS)
{
if (retries != 0)
{
retries--;
goto WinDivertDriverInstallReTry;
}
}
goto WinDivertDriverInstallExit;
}
WinDivertDriverInstallExit:
if (service != NULL)
{
// Start the service:
if (!StartService(service, 0, NULL))
{
err = GetLastError();
if (err == ERROR_SERVICE_ALREADY_RUNNING)
{
SetLastError(0);
}
else
{
// Failed to start service; clean-up:
ControlService(service, SERVICE_CONTROL_STOP, &status);
DeleteService(service);
CloseServiceHandle(service);
service = NULL;
SetLastError(err);
}
}
}
err = GetLastError();
if (manager != NULL)
{
CloseServiceHandle(manager);
}
SetLastError(err);
return service;
}