检查是否使用C安装了服务
我正在编写一个创建Windows服务的C应用程序。 我想在尝试调用安装function之前检查服务是否已安装,但我无法找到如何检查它。
我已经编写了上面的代码来尝试:
DWORD InstallMyService() { char strDir[1024 + 1]; SC_HANDLE schSCManager; SC_HANDLE schService; LPCTSTR lpszBinaryPathName; if (GetCurrentDirectory(1024, strDir) == 0) { aff_error("GetCurrentDirectory"); return FALSE; } strcat(strDir, "\\"MY_SERVICE_BIN_NAME); if ((schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) == NULL) { printf("Error OpenSCManager : %d\n", GetLastError()); return FALSE; } lpszBinaryPathName = strDir; schService = CreateService(schSCManager, MY_SERVICE_NAME, MY_SERVICE_DESCRIPTOR, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, lpszBinaryPathName, NULL, NULL, NULL, NULL, NULL); if (schService == NULL) { printf("Error CreateService : %d\n", GetLastError()); return FALSE; } CloseServiceHandle(schService); return TRUE; }
但是此代码不会检测服务是否仍然存在。 有人知道要调用哪个函数吗? 我发现很多post都在谈论这个,但不是在C中,只在C#或VB中。
谢谢。
可能的方法是始终尝试CreateService()
,如果失败则查询GetLastError()
并检查它是否等于ERROR_SERVICE_EXISTS
:
SC_HANDLE service_handle = CreateService(...); if (0 == service_handle) { if (ERROR_SERVICE_EXISTS == GetLastError()) { /* Handle service already exists. */ } else { /* Handle failure. */ } }
这需要对代码进行轻微更改,使两个函数InstallService()
和CheckService()
具有一个函数(例如) EnsureServiceInstalled()
。
或者,您可以使用OpenService()
函数,该函数将使用ERROR_SERVICE_DOES_NOT_EXIST
GetLastError()
代码失败:
SC_HANDLE scm_handle = OpenSCManager(0, 0, GENERIC_READ); if (scm_handle) { SC_HANDLE service_handle = OpenService(scm_handle, "the-name-of-your-service", GENERIC_READ); if (!service_handle) { if (ERROR_SERVICE_DOES_NOT_EXIST != GetLastError()) { fprintf(stderr, "Failed to OpenService(): %d\n", GetLastError()); } else { /* Service does not exist. */ fprintf(stderr, "Service does not exist.\n"); } } else { fprintf(stderr, "Opened service.\n"); CloseServiceHandle(service_handle); } CloseServiceHandle(scm_handle); } else { fprintf(stderr, "Failed to OpenSCManager(): %d\n", GetLastError()); }
如果您需要是/否答案是否已安装服务或注释,请使用以下function:
bool IsServiceInstalled(LPWSTR ServiceName) { bool serviceInstalled = false; SC_HANDLE scm_handle = OpenSCManager(0, 0, SC_MANAGER_CONNECT); if (scm_handle) { SC_HANDLE service_handle = OpenService(scm_handle, ServiceName, SERVICE_INTERROGATE); if (service_handle != NULL) { wprintf(L"Service Installed\n"); serviceInstalled = true; CloseServiceHandle(service_handle); } else { wprintf(_T("OpenService failed - service not installed\n")); } CloseServiceHandle(scm_handle); } else wprintf(_T("OpenService couldn't open - service not installed\n")); return serviceInstalled; }
尝试使用QueryServiceStatusEx
见这里的例子