本文整理汇总了C++中OpenSCManager函数的典型用法代码示例。如果您正苦于以下问题:C++ OpenSCManager函数的具体用法?C++ OpenSCManager怎么用?C++ OpenSCManager使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了OpenSCManager函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: _tcscpy_s
BOOLEAN ScmDrvCtrl::Install(const TCHAR* lpszServiceName, const TCHAR* lpszDriverPath, const TCHAR* lpszAltitude, const TCHAR* lpszLink_name)
{
SC_HANDLE hServiceMgr = NULL;
SC_HANDLE hService = NULL;
int i = 0;
_tcscpy_s(m_link_name, MAX_PATH, lpszLink_name);
if (NULL == lpszServiceName || NULL == lpszDriverPath || NULL == lpszAltitude)
{
return FALSE;
}
UnInstall(lpszServiceName);
WIN32_FIND_DATA FindFileData;
if (FindFirstFileW(lpszDriverPath, &FindFileData) == INVALID_HANDLE_VALUE)
{
return FALSE;
}
again:
hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hServiceMgr == NULL)
{
return FALSE;
}
hService = CreateService(hServiceMgr,
lpszServiceName, // 驱动程序的在注册表中的名字
lpszServiceName, // 注册表驱动程序的DisplayName 值
SERVICE_ALL_ACCESS, // 加载驱动程序的访问权限
SERVICE_FILE_SYSTEM_DRIVER, // 表示加载的服务是文件系统驱动程序
SERVICE_DEMAND_START, // 注册表驱动程序的Start 值
SERVICE_ERROR_IGNORE, // 注册表驱动程序的ErrorControl 值
lpszDriverPath, // 注册表驱动程序的ImagePath 值
_T("FSFilter Activity Monitor"),// 注册表驱动程序的Group 值
NULL,
_T("FltMgr"), // 注册表驱动程序的DependOnService 值
NULL,
NULL);
if (hService == NULL)
{
CloseServiceHandle(hServiceMgr);
if (i > 100000)
{
return FALSE;
}
i++;
// printf("%d\n", i);
goto again;
}
CloseServiceHandle(hService); // 服务句柄
CloseServiceHandle(hServiceMgr); // SCM句柄
TCHAR szTempStr[MAX_PATH];
HKEY hKey = NULL;
DWORD dwData = 0;
_tcscpy_s(szTempStr, MAX_PATH, _T("SYSTEM\\CurrentControlSet\\Services\\"));
_tcscat_s(szTempStr, MAX_PATH, lpszServiceName);
if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS)
{
return FALSE;
}
_tcscpy_s(szTempStr, MAX_PATH, lpszServiceName);
if (RegSetValueEx(hKey, _T("service_name"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS)
{
return FALSE;
}
//GetWindowsDirectory(szTempStr,MAX_PATH);
//if (RegSetValueEx(hKey, _T("system_dir"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS)
//{
// return FALSE;
//}
RegFlushKey(hKey);
RegCloseKey(hKey);
_tcscpy_s(szTempStr, MAX_PATH, _T("SYSTEM\\CurrentControlSet\\Services\\"));
_tcscat_s(szTempStr, MAX_PATH, lpszServiceName);
_tcscat_s(szTempStr, MAX_PATH, _T("\\Instances"));
if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS)
{
return FALSE;
}
_tcscpy_s(szTempStr, MAX_PATH, lpszServiceName);
_tcscat_s(szTempStr, MAX_PATH, _T(" Instance"));
if (RegSetValueEx(hKey, _T("DefaultInstance"), 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)_tcslen(szTempStr)*sizeof(TCHAR)) != ERROR_SUCCESS)
{
return FALSE;
}
RegFlushKey(hKey);
RegCloseKey(hKey);
_tcscpy_s(szTempStr, MAX_PATH, _T("SYSTEM\\CurrentControlSet\\Services\\"));
_tcscat_s(szTempStr, MAX_PATH, lpszServiceName);
_tcscat_s(szTempStr, MAX_PATH, _T("\\Instances\\"));
_tcscat_s(szTempStr, MAX_PATH, lpszServiceName);
_tcscat_s(szTempStr, MAX_PATH, _T(" Instance"));
if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS)
//.........这里部分代码省略.........
示例2: 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;
}
示例3: UtilLoadDriver
BOOL
UtilLoadDriver(
_In_ LPTSTR szDriverName,
_In_ LPTSTR szDriverFileName,
_In_ LPTSTR szWin32DeviceName,
_Out_ HANDLE *pDriver
)
/*++
Routine Description:
This routine uses the Service Control Manager APIs to create an entry
for a standalone driver. It then opens a handle to the driver.
The driver is assumed to be in the current directory.
NOTE: This routine creates an entry for a standalone driver. If this
is modified for use with a driver that requires a Tag, Group, and/or
Dependencies, it may be necessary to query the registry for existing
driver information (in order to determine a unique Tag, etc.).
Arguments:
szDriverName - name of the driver (no extension)
szDriverFileName - name of driver (with extension)
szWin32DeviceName - Name of driver (no extension) prefixed with \\.\
pDriver - pointer to a variable that receives the handle to the driver
Return Value:
TRUE if driver is loaded successfully.
--*/
{
BOOL ReturnValue = FALSE;
TCHAR* pPathSeparator;
TCHAR szDriverPath[MAX_PATH] = _T("");
DWORD dwSize;
SC_HANDLE hSCM = NULL;
HANDLE hDriver = NULL;
*pDriver = NULL;
//
// Construct driver path.
//
dwSize = GetModuleFileName(NULL, szDriverPath, ARRAY_LENGTH(szDriverPath));
if (dwSize == 0) {
ErrorPrint("GetModuleFileName failed, last error 0x%u", GetLastError());
goto Exit;
}
pPathSeparator = _tcsrchr(szDriverPath, _T('\\'));
if (pPathSeparator != NULL) {
pPathSeparator[1] = _T('\0');
_tcscat_s(szDriverPath, MAX_PATH, szDriverFileName);
} else {
ErrorPrint("_tcsrchr failed to file \\ in driver path.");
goto Exit;
}
//
// Get a handle to SCM
//
hSCM = OpenSCManager ( NULL, NULL, SC_MANAGER_ALL_ACCESS );
if (hSCM == NULL) {
ErrorPrint("OpenSCManager failed, last error 0x%x", GetLastError());
goto Exit;
}
//
// First, uninstall and unload the driver.
//
ReturnValue = UtilUnloadDriver( INVALID_HANDLE_VALUE, hSCM, szDriverName);
if (ReturnValue != TRUE) {
ErrorPrint("UnloadDriver failed");
goto Exit;
}
//
// Install the driver.
//
ReturnValue = UtilCreateService(hSCM, szDriverName, szDriverPath);
if (ReturnValue == FALSE) {
ErrorPrint("UtilCreateService failed");
goto Exit;
}
//
//.........这里部分代码省略.........
示例4: InstallService
//
// FUNCTION: InstallService
//
// PURPOSE: Install the current application as a service to the local
// service control manager database.
//
// PARAMETERS:
// * pszServiceName - the name of the service to be installed
// * pszDisplayName - the display name of the service
// * dwStartType - the service start option. This parameter can be one of
// the following values: SERVICE_AUTO_START, SERVICE_BOOT_START,
// SERVICE_DEMAND_START, SERVICE_DISABLED, SERVICE_SYSTEM_START.
// * pszDependencies - a pointer to a double null-terminated array of null-
// separated names of services or load ordering groups that the system
// must start before this service.
// * pszAccount - the name of the account under which the service runs.
// * pszPassword - the password to the account name.
//
// NOTE: If the function fails to install the service, it prints the error
// in the standard output stream for users to diagnose the problem.
//
void InstallService(PWSTR pszServiceName,
PWSTR pszDisplayName,
DWORD dwStartType,
PWSTR pszDependencies,
PWSTR pszAccount,
PWSTR pszPassword)
{
wchar_t szPath[MAX_PATH];
SC_HANDLE schSCManager = NULL;
SC_HANDLE schService = NULL;
if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)) == 0)
{
wprintf(L"GetModuleFileName failed w/err 0x%08lx\n", GetLastError());
goto Cleanup;
}
// Open the local default service control manager database
schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT |
SC_MANAGER_CREATE_SERVICE);
if (schSCManager == NULL)
{
wprintf(L"OpenSCManager failed w/err 0x%08lx\n", GetLastError());
goto Cleanup;
}
// Install the service into SCM by calling CreateService
schService = CreateService(
schSCManager, // SCManager database
pszServiceName, // Name of service
pszDisplayName, // Name to display
SERVICE_QUERY_STATUS, // Desired access
SERVICE_WIN32_OWN_PROCESS, // Service type
dwStartType, // Service start type
SERVICE_ERROR_NORMAL, // Error control type
szPath, // Service's binary
NULL, // No load ordering group
NULL, // No tag identifier
pszDependencies, // Dependencies
pszAccount, // Service running account
pszPassword // Password of the account
);
if (schService == NULL)
{
wprintf(L"CreateService failed w/err 0x%08lx\n", GetLastError());
goto Cleanup;
}
wprintf(L"%s is installed.\n", pszServiceName);
Cleanup:
// Centralized cleanup for all allocated resources.
if (schSCManager)
{
CloseServiceHandle(schSCManager);
schSCManager = NULL;
}
if (schService)
{
CloseServiceHandle(schService);
schService = NULL;
}
}
示例5: InstallService
// Invoked with the /INSTALL switch. Installs LightRepeater Engine as a
// Windows NT Service using Service Control Manager.
EXTERN_C int WINAPI InstallService(int argc, char **argv)
{
if (argc > 4)
puts("InstallService(): Too many parameters.");
LPSTR pcMachineName = NULL;
if (argc >= 4)
pcMachineName = argv[argc-1];
const char cRunServiceSwitch[] = "\" /RUNSERVICE";
char cImagePath[MAX_PATH+sizeof(cRunServiceSwitch)+2] = "\"";
if (argv[2])
strncpy(cImagePath+1, argv[2], MAX_PATH);
else
GetModuleFileName(NULL, cImagePath+1, MAX_PATH);
strcat(cImagePath, cRunServiceSwitch);
if (argc > 4)
{
if (strlen(cImagePath)+strlen(argv[3])+4 > sizeof(cImagePath))
{
fputs("Too long parameter.\r\n", stderr);
return 1;
}
strcat(cImagePath, " \"");
strcat(cImagePath, argv[3]);
strcat(cImagePath, "\"");
}
puts("Opening Service Control Manager...");
SC_HANDLE hSC = OpenSCManager(pcMachineName, NULL,
SC_MANAGER_CREATE_SERVICE);
if (hSC == NULL)
{
if (win_errno == ERROR_CALL_NOT_IMPLEMENTED)
fputs("Error: There is no Service Control Manager available in this "
"operating system.\r\n", stderr);
else
win_perror();
return 1;
}
puts("Creating service...");
SC_HANDLE hService = CreateService(hSC, LR_SERVICE_NAME,
LR_SERVICE_DESCRIPTION, 0,
SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL, cImagePath, NULL, NULL, NULL, NULL, NULL);
if (hService)
{
puts("Service install successful.");
CloseServiceHandle(hService);
CloseServiceHandle(hSC);
return 0;
}
else
{
win_perror();
CloseServiceHandle(hSC);
return 1;
}
}
示例6: StartPortTalkDriver
unsigned char StartPortTalkDriver(void)
{
SC_HANDLE SchSCManager;
SC_HANDLE schService;
BOOL ret;
DWORD err;
/* Open Handle to Service Control Manager */
SchSCManager = OpenSCManager (NULL, /* machine (NULL == local) */
NULL, /* database (NULL == default) */
SC_MANAGER_ALL_ACCESS); /* access required */
if (SchSCManager == NULL)
if (GetLastError() == ERROR_ACCESS_DENIED) {
/* We do not have enough rights to open the SCM, therefore we must */
/* be a poor user with only user rights. */
printf("PortTalk: You do not have rights to access the Service Control Manager and\n");
printf("PortTalk: the PortTalk driver is not installed or started. Please ask \n");
printf("PortTalk: your administrator to install the driver on your behalf.\n");
return(0);
}
do {
/* Open a Handle to the PortTalk Service Database */
schService = OpenService(SchSCManager, /* handle to service control manager database */
"PortTalk", /* pointer to name of service to start */
SERVICE_ALL_ACCESS); /* type of access to service */
if (schService == NULL)
switch (GetLastError()) {
case ERROR_ACCESS_DENIED:
printf("PortTalk: You do not have rights to the PortTalk service database\n");
return(0);
case ERROR_INVALID_NAME:
printf("PortTalk: The specified service name is invalid.\n");
return(0);
case ERROR_SERVICE_DOES_NOT_EXIST:
printf("PortTalk: The PortTalk driver does not exist. Installing driver.\n");
printf("PortTalk: This can take up to 30 seconds on some machines . .\n");
InstallPortTalkDriver();
break;
}
} while (schService == NULL);
/* Start the PortTalk Driver. Errors will occur here if PortTalk.SYS file doesn't exist */
ret = StartService (schService, /* service identifier */
0, /* number of arguments */
NULL); /* pointer to arguments */
if (ret) printf("PortTalk: The PortTalk driver has been successfully started.\n");
else {
err = GetLastError();
if (err == ERROR_SERVICE_ALREADY_RUNNING)
printf("PortTalk: The PortTalk driver is already running.\n");
else {
printf("PortTalk: Unknown error while starting PortTalk driver service.\n");
printf("PortTalk: Does PortTalk.SYS exist in your \\System32\\Drivers Directory?\n");
return(0);
}
}
/* Close handle to Service Control Manager */
CloseServiceHandle (schService);
return(TRUE);
}
示例7: NewSvr
DLLEXP bool NewSvr(PSvrHnds pSH)
{
bool bSuccess = false;
char FullName[MAX_PATH];
if(pSH == NULL)
{
PRINT("[%s]error : pSH == NULL!\n",__func__);
goto QUIT;
}
pSH->hSCM = OpenSCManager(NULL,NULL,SC_MANAGER_CREATE_SERVICE);
if(!pSH->hSCM)
{
PRINT("[%s]error : OpenSCManager Failed!\n",\
__func__);
goto QUIT;
}
if(GetFullPathName(SYSNAME,sizeof(FullName),\
FullName,NULL) < strlen(SYSNAME)+1)
{
PRINT("[%s]error : Get SYS FullPathName Failed!\n",\
__func__);
goto QUIT;
}
pSH->hSVR = CreateService(pSH->hSCM,SVRNAME,SVRNOTE,\
SERVICE_ALL_ACCESS,SERVICE_KERNEL_DRIVER,\
SERVICE_DEMAND_START,SERVICE_ERROR_IGNORE,\
FullName,NULL,NULL,NULL,NULL,NULL);
if(!pSH->hSVR && GetLastError() == ERROR_SERVICE_EXISTS)
{
PRINT("[%s]msg : Servicr Existed , Try To Open!\n",\
__func__);
pSH->hSVR = OpenService(pSH->hSCM,SVRNAME,\
SERVICE_ALL_ACCESS);
if(!pSH->hSVR)
{
PRINT("[%s]err : OpenService Failed!\n",\
__func__);
goto QUIT;
}
}
else if(!pSH->hSVR)
{
PRINT("[%s]error : CreateService Failed!\n",\
__func__);
goto QUIT;
}
bSuccess = true;
QUIT:
if(!bSuccess)
{
if(pSH->hSCM)
CloseServiceHandle(pSH->hSCM);
if(pSH->hSVR)
CloseServiceHandle(pSH->hSVR);
}
return bSuccess;
}
示例8: ServiceController
ServiceController()
{
_scManager = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );
}
示例9: _tWinMain
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
if( lpCmdLine[0] == _T('-') || lpCmdLine[0] == _T('/') ){
if( lstrcmpi(_T("install"), lpCmdLine + 1) == 0 ){
bool installed = false;
TCHAR exePath[512];
if( GetModuleFileName(NULL, exePath, _countof(exePath)) != 0 ){
SC_HANDLE hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE);
if( hScm != NULL ){
SC_HANDLE hSrv = CreateService(
hScm, SERVICE_NAME, SERVICE_NAME, 0, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, exePath, NULL, NULL, NULL, NULL, NULL);
if( hSrv != NULL ){
installed = true;
CloseServiceHandle(hSrv);
}
CloseServiceHandle(hScm);
}
}
if( installed == false ){
//コンソールがないのでメッセージボックスで伝える
MessageBox(NULL, L"Failed to install/remove " SERVICE_NAME L".\r\nRun as Administrator on Vista and later.", NULL, MB_ICONERROR);
}
return 0;
}else if( lstrcmpi(_T("remove"), lpCmdLine + 1) == 0 ){
bool removed = false;
SC_HANDLE hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if( hScm != NULL ){
SC_HANDLE hSrv = OpenService(hScm, SERVICE_NAME, DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
if( hSrv != NULL ){
SERVICE_STATUS srvStatus;
if( QueryServiceStatus(hSrv, &srvStatus) != FALSE ){
if( srvStatus.dwCurrentState == SERVICE_STOPPED || ControlService(hSrv, SERVICE_CONTROL_STOP, &srvStatus) != FALSE ){
removed = DeleteService(hSrv) != FALSE;
}
}
CloseServiceHandle(hSrv);
}
CloseServiceHandle(hScm);
}
if( removed == false ){
MessageBox(NULL, L"Failed to install/remove " SERVICE_NAME L".\r\nRun as Administrator on Vista and later.", NULL, MB_ICONERROR);
}
return 0;
}
}
if( IsInstallService(SERVICE_NAME) == FALSE ){
//普通にexeとして起動を行う
HANDLE hMutex = CreateMutex(NULL, TRUE, EPG_TIMER_BON_SRV_MUTEX);
if( hMutex != NULL ){
if( GetLastError() != ERROR_ALREADY_EXISTS ){
StartDebugLog();
//メインスレッドに対するCOMの初期化
CoInitialize(NULL);
CEpgTimerSrvMain* pMain = new CEpgTimerSrvMain;
if( pMain->Main(false) == false ){
OutputDebugString(_T("_tWinMain(): Failed to start\r\n"));
}
delete pMain;
CoUninitialize();
StopDebugLog();
}
ReleaseMutex(hMutex);
CloseHandle(hMutex);
}
}else if( IsStopService(SERVICE_NAME) == FALSE ){
//サービスとして実行
HANDLE hMutex = CreateMutex(NULL, TRUE, EPG_TIMER_BON_SRV_MUTEX);
if( hMutex != NULL ){
if( GetLastError() != ERROR_ALREADY_EXISTS ){
StartDebugLog();
SERVICE_TABLE_ENTRY dispatchTable[] = {
{ SERVICE_NAME, service_main },
{ NULL, NULL }
};
if( StartServiceCtrlDispatcher(dispatchTable) == FALSE ){
OutputDebugString(_T("_tWinMain(): StartServiceCtrlDispatcher failed\r\n"));
}
StopDebugLog();
}
ReleaseMutex(hMutex);
CloseHandle(hMutex);
}
}else{
//Stop状態なのでサービスの開始を要求
bool started = false;
SC_HANDLE hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if( hScm != NULL ){
SC_HANDLE hSrv = OpenService(hScm, SERVICE_NAME, SERVICE_START);
if( hSrv != NULL ){
started = StartService(hSrv, 0, NULL) != FALSE;
CloseServiceHandle(hSrv);
}
CloseServiceHandle(hScm);
}
//.........这里部分代码省略.........
示例10: install_service
BOOL install_service()
{
SC_HANDLE hSCManager;
SC_HANDLE hService;
char path[MAX_PATH];
// Get the current module name
if (!GetModuleFileName(NULL, path, MAX_PATH)) {
printf("Cannot get module name (0x%08x)\n", GetLastError());
return FALSE;
}
// Build the service command line
char cmd[MAX_PATH];
int len = _snprintf(cmd, sizeof(cmd), "\"%s\" service", path);
if (len < 0 || len == sizeof(cmd)) {
printf("Cannot build service command line (0x%08x)\n", -1);
return FALSE;
}
// Open the service manager
hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (hSCManager == NULL) {
printf("Cannot open service manager (0x%08x)\n", GetLastError());
return FALSE;
}
printf(" * Installing service %s\n", SERVICE_NAME);
fflush(stdout);
// Create the service
hService = CreateService(
hSCManager,
SERVICE_NAME,
DISPLAY_NAME,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
cmd,
NULL,
NULL,
NULL,
NULL, /* LocalSystem account */
NULL
);
if (hService == NULL) {
printf("Cannot create service (0x%08x)\n", GetLastError());
CloseServiceHandle(hSCManager);
return FALSE;
}
// Start the service
printf(" * Starting service\n");
fflush(stdout);
char* args[] = { path, "service" };
if (StartService(hService, 2, (const char**)&args) == 0) {
DWORD err = GetLastError();
if (err != ERROR_SERVICE_ALREADY_RUNNING) {
printf("Cannot start service %s (0x%08x)\n", SERVICE_NAME, err);
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
return FALSE;
}
}
// Cleanup
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
printf("Service %s successfully installed.\n", SERVICE_NAME);
fflush(stdout);
return TRUE;
}
示例11: SERVICE_DISCOVERY
int SERVICE_DISCOVERY(AGENT_REQUEST *request, AGENT_RESULT *result)
{
ENUM_SERVICE_STATUS_PROCESS *ssp = NULL;
QUERY_SERVICE_CONFIG *qsc = NULL;
SERVICE_DESCRIPTION *scd = NULL;
SC_HANDLE h_mgr;
DWORD sz = 0, szn, i, k, services, resume_handle = 0;
char *utf8;
struct zbx_json j;
if (NULL == (h_mgr = OpenSCManager(NULL, NULL, GENERIC_READ)))
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot obtain system information."));
return SYSINFO_RET_FAIL;
}
zbx_json_init(&j, ZBX_JSON_STAT_BUF_LEN);
zbx_json_addarray(&j, ZBX_PROTO_TAG_DATA);
while (0 != EnumServicesStatusEx(h_mgr, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL,
(LPBYTE)ssp, sz, &szn, &services, &resume_handle, NULL) || ERROR_MORE_DATA == GetLastError())
{
for (i = 0; i < services; i++)
{
SC_HANDLE h_srv;
DWORD current_state;
if (NULL == (h_srv = OpenService(h_mgr, ssp[i].lpServiceName, SERVICE_QUERY_CONFIG)))
continue;
QueryServiceConfig(h_srv, NULL, 0, &sz);
if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
{
zabbix_log(LOG_LEVEL_DEBUG, "cannot obtain configuration of service \"%s\": %s",
ssp[i].lpServiceName, strerror_from_system(GetLastError()));
goto next;
}
qsc = (QUERY_SERVICE_CONFIG *)zbx_malloc(qsc, sz);
if (0 == QueryServiceConfig(h_srv, qsc, sz, &sz))
{
zabbix_log(LOG_LEVEL_DEBUG, "cannot obtain configuration of service \"%s\": %s",
ssp[i].lpServiceName, strerror_from_system(GetLastError()));
goto next;
}
QueryServiceConfig2(h_srv, SERVICE_CONFIG_DESCRIPTION, NULL, 0, &sz);
if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
{
zabbix_log(LOG_LEVEL_DEBUG, "cannot obtain description of service \"%s\": %s",
ssp[i].lpServiceName, strerror_from_system(GetLastError()));
goto next;
}
scd = (SERVICE_DESCRIPTION *)zbx_malloc(scd, sz);
if (0 == QueryServiceConfig2(h_srv, SERVICE_CONFIG_DESCRIPTION, (LPBYTE)scd, sz, &sz))
{
zabbix_log(LOG_LEVEL_DEBUG, "cannot obtain description of service \"%s\": %s",
ssp[i].lpServiceName, strerror_from_system(GetLastError()));
goto next;
}
zbx_json_addobject(&j, NULL);
utf8 = zbx_unicode_to_utf8(ssp[i].lpServiceName);
zbx_json_addstring(&j, "{#SERVICE.NAME}", utf8, ZBX_JSON_TYPE_STRING);
zbx_free(utf8);
utf8 = zbx_unicode_to_utf8(ssp[i].lpDisplayName);
zbx_json_addstring(&j, "{#SERVICE.DISPLAYNAME}", utf8, ZBX_JSON_TYPE_STRING);
zbx_free(utf8);
if (NULL != scd->lpDescription)
{
utf8 = zbx_unicode_to_utf8(scd->lpDescription);
zbx_json_addstring(&j, "{#SERVICE.DESCRIPTION}", utf8, ZBX_JSON_TYPE_STRING);
zbx_free(utf8);
}
else
zbx_json_addstring(&j, "{#SERVICE.DESCRIPTION}", "", ZBX_JSON_TYPE_STRING);
current_state = ssp[i].ServiceStatusProcess.dwCurrentState;
for (k = 0; k < ARRSIZE(service_states) && current_state != service_states[k]; k++)
;
zbx_json_adduint64(&j, "{#SERVICE.STATE}", k);
zbx_json_addstring(&j, "{#SERVICE.STATENAME}", get_state_string(current_state),
ZBX_JSON_TYPE_STRING);
utf8 = zbx_unicode_to_utf8(qsc->lpBinaryPathName);
zbx_json_addstring(&j, "{#SERVICE.PATH}", utf8, ZBX_JSON_TYPE_STRING);
zbx_free(utf8);
utf8 = zbx_unicode_to_utf8(qsc->lpServiceStartName);
zbx_json_addstring(&j, "{#SERVICE.USER}", utf8, ZBX_JSON_TYPE_STRING);
zbx_free(utf8);
//.........这里部分代码省略.........
示例12: main
int main(int argc, char *argv[]) {
char *bslash;
VerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&VerInfo);
if (argc < 2) {
show_usage();
return -1;
}
hAdvapi = LoadLibrary("advapi32.dll");
uChangeServiceConfig2 = (UCHANGESERVICECONFIG2)GetProcAddress(hAdvapi, "ChangeServiceConfig2A");
if (!stricmp(argv[1], "install")) {
SC_HANDLE hService, hSCManager;
char path[MAX_PATH+1];
char binpath[MAX_PATH+1];
hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (!hSCManager) {
exit(0);
}
GetModuleFileName(NULL,path,MAX_PATH);
if ((bslash = strrchr(path, '\\')))
*bslash = 0;
strcpy(binpath,path);
strcat(binpath, "\\wircd.exe");
hService = CreateService(hSCManager, "UnrealIRCd", "UnrealIRCd",
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, binpath,
NULL, NULL, NULL, NULL, NULL);
if (hService)
{
printf("UnrealIRCd NT Service successfully installed");
if (VerInfo.dwMajorVersion >= 5) {
SERVICE_DESCRIPTION info;
info.lpDescription = "Internet Relay Chat Server. Allows users to chat with eachother via an IRC client.";
uChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &info);
}
CloseServiceHandle(hService);
} else
printf("Failed to install UnrealIRCd NT Service - %s", show_error(GetLastError()));
CloseServiceHandle(hSCManager);
return 0;
}
else if (!stricmp(argv[1], "uninstall")) {
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", DELETE);
if (DeleteService(hService))
printf("UnrealIRCd NT Service successfully uninstalled");
else
printf("Failed to uninstall UnrealIRCd NT Service - %s", show_error(GetLastError()));
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
return 0;
}
else if (!stricmp(argv[1], "start")) {
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_START);
if (StartService(hService, 0, NULL))
printf("UnrealIRCd NT Service successfully started");
else
printf("Failed to start UnrealIRCd NT Service - %s", show_error(GetLastError()));
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
return 0;
}
else if (!stricmp(argv[1], "stop")) {
SERVICE_STATUS status;
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_STOP);
ControlService(hService, SERVICE_CONTROL_STOP, &status);
printf("UnrealIRCd NT Service successfully stopped");
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
return 0;
}
else if (!stricmp(argv[1], "restart")) {
SERVICE_STATUS status;
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_STOP|SERVICE_START);
ControlService(hService, SERVICE_CONTROL_STOP, &status);
if (StartService(hService, 0, NULL))
printf("UnrealIRCd NT Service successfully restarted");
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
return 0;
}
else if (!stricmp(argv[1], "rehash")) {
SERVICE_STATUS status;
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_USER_DEFINED_CONTROL);
ControlService(hService, IRCD_SERVICE_CONTROL_REHASH, &status);
printf("UnrealIRCd NT Service successfully rehashed");
}
else if (!stricmp(argv[1], "config")) {
SERVICE_STATUS status;
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd",
SERVICE_CHANGE_CONFIG|SERVICE_START);
if (argc < 3) {
show_usage();
//.........这里部分代码省略.........
示例13: SERVICES
int SERVICES(AGENT_REQUEST *request, AGENT_RESULT *result)
{
int start_type, service_state;
char *type, *state, *exclude, *buf = NULL, *utf8;
SC_HANDLE h_mgr;
ENUM_SERVICE_STATUS_PROCESS *ssp = NULL;
DWORD sz = 0, szn, i, services, resume_handle = 0;
if (3 < request->nparam)
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Too many parameters."));
return SYSINFO_RET_FAIL;
}
type = get_rparam(request, 0);
state = get_rparam(request, 1);
exclude = get_rparam(request, 2);
if (NULL == type || '\0' == *type || 0 == strcmp(type, "all")) /* default parameter */
start_type = ZBX_SRV_STARTTYPE_ALL;
else if (0 == strcmp(type, "automatic"))
start_type = ZBX_SRV_STARTTYPE_AUTOMATIC;
else if (0 == strcmp(type, "manual"))
start_type = ZBX_SRV_STARTTYPE_MANUAL;
else if (0 == strcmp(type, "disabled"))
start_type = ZBX_SRV_STARTTYPE_DISABLED;
else
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid first parameter."));
return SYSINFO_RET_FAIL;
}
if (NULL == state || '\0' == *state || 0 == strcmp(state, "all")) /* default parameter */
service_state = ZBX_SRV_STATE_ALL;
else if (0 == strcmp(state, "stopped"))
service_state = ZBX_SRV_STATE_STOPPED;
else if (0 == strcmp(state, "started"))
service_state = ZBX_SRV_STATE_STARTED;
else if (0 == strcmp(state, "start_pending"))
service_state = ZBX_SRV_STATE_START_PENDING;
else if (0 == strcmp(state, "stop_pending"))
service_state = ZBX_SRV_STATE_STOP_PENDING;
else if (0 == strcmp(state, "running"))
service_state = ZBX_SRV_STATE_RUNNING;
else if (0 == strcmp(state, "continue_pending"))
service_state = ZBX_SRV_STATE_CONTINUE_PENDING;
else if (0 == strcmp(state, "pause_pending"))
service_state = ZBX_SRV_STATE_PAUSE_PENDING;
else if (0 == strcmp(state, "paused"))
service_state = ZBX_SRV_STATE_PAUSED;
else
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid second parameter."));
return SYSINFO_RET_FAIL;
}
if (NULL == (h_mgr = OpenSCManager(NULL, NULL, GENERIC_READ)))
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot obtain system information."));
return SYSINFO_RET_FAIL;
}
while (0 != EnumServicesStatusEx(h_mgr, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL,
(LPBYTE)ssp, sz, &szn, &services, &resume_handle, NULL) || ERROR_MORE_DATA == GetLastError())
{
for (i = 0; i < services; i++)
{
SC_HANDLE h_srv;
if (NULL == (h_srv = OpenService(h_mgr, ssp[i].lpServiceName,
SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG)))
{
continue;
}
if (SUCCEED == check_service_starttype(h_srv, start_type))
{
if (SUCCEED == check_service_state(h_srv, service_state))
{
utf8 = zbx_unicode_to_utf8(ssp[i].lpServiceName);
if (NULL == exclude || FAIL == str_in_list(exclude, utf8, ','))
buf = zbx_strdcatf(buf, "%s\n", utf8);
zbx_free(utf8);
}
}
CloseServiceHandle(h_srv);
}
if (0 == szn)
break;
if (NULL == ssp)
{
sz = szn;
ssp = (ENUM_SERVICE_STATUS_PROCESS *)zbx_malloc(ssp, sz);
}
}
//.........这里部分代码省略.........
示例14: SERVICE_STATE
int SERVICE_STATE(AGENT_REQUEST *request, AGENT_RESULT *result)
{
SC_HANDLE mgr, service;
char *name;
wchar_t *wname;
wchar_t service_name[MAX_STRING_LEN];
DWORD max_len_name = MAX_STRING_LEN;
int i;
SERVICE_STATUS status;
if (1 < request->nparam)
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Too many parameters."));
return SYSINFO_RET_FAIL;
}
name = get_rparam(request, 0);
if (NULL == name || '\0' == *name)
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid first parameter."));
return SYSINFO_RET_FAIL;
}
if (NULL == (mgr = OpenSCManager(NULL, NULL, GENERIC_READ)))
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot obtain system information."));
return SYSINFO_RET_FAIL;
}
wname = zbx_utf8_to_unicode(name);
service = OpenService(mgr, wname, SERVICE_QUERY_STATUS);
if (NULL == service && 0 != GetServiceKeyName(mgr, wname, service_name, &max_len_name))
service = OpenService(mgr, service_name, SERVICE_QUERY_STATUS);
zbx_free(wname);
if (NULL == service)
{
SET_UI64_RESULT(result, 255);
}
else
{
if (0 != QueryServiceStatus(service, &status))
{
for (i = 0; i < ARRSIZE(service_states) && status.dwCurrentState != service_states[i]; i++)
;
SET_UI64_RESULT(result, i);
}
else
SET_UI64_RESULT(result, 7);
CloseServiceHandle(service);
}
CloseServiceHandle(mgr);
return SYSINFO_RET_OK;
}
示例15: SERVICE_INFO
int SERVICE_INFO(AGENT_REQUEST *request, AGENT_RESULT *result)
{
QUERY_SERVICE_CONFIG *qsc = NULL;
SERVICE_DESCRIPTION *scd = NULL;
SERVICE_STATUS status;
SC_HANDLE h_mgr, h_srv;
DWORD sz = 0;
int param_type, i;
char *name, *param;
wchar_t *wname, service_name[MAX_STRING_LEN];
DWORD max_len_name = MAX_STRING_LEN;
if (2 < request->nparam)
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Too many parameters."));
return SYSINFO_RET_FAIL;
}
name = get_rparam(request, 0);
param = get_rparam(request, 1);
if (NULL == name || '\0' == *name)
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid first parameter."));
return SYSINFO_RET_FAIL;
}
if (NULL == param || '\0' == *param || 0 == strcmp(param, "state")) /* default second parameter */
param_type = ZBX_SRV_PARAM_STATE;
else if (0 == strcmp(param, "displayname"))
param_type = ZBX_SRV_PARAM_DISPLAYNAME;
else if (0 == strcmp(param, "path"))
param_type = ZBX_SRV_PARAM_PATH;
else if (0 == strcmp(param, "user"))
param_type = ZBX_SRV_PARAM_USER;
else if (0 == strcmp(param, "startup"))
param_type = ZBX_SRV_PARAM_STARTUP;
else if (0 == strcmp(param, "description"))
param_type = ZBX_SRV_PARAM_DESCRIPTION;
else
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid second parameter."));
return SYSINFO_RET_FAIL;
}
if (NULL == (h_mgr = OpenSCManager(NULL, NULL, GENERIC_READ)))
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot obtain system information."));
return SYSINFO_RET_FAIL;
}
wname = zbx_utf8_to_unicode(name);
h_srv = OpenService(h_mgr, wname, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG);
if (NULL == h_srv && 0 != GetServiceKeyName(h_mgr, wname, service_name, &max_len_name))
h_srv = OpenService(h_mgr, service_name, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG);
zbx_free(wname);
if (NULL == h_srv)
{
int ret;
if (ZBX_SRV_PARAM_STATE == param_type)
{
SET_UI64_RESULT(result, 255);
ret = SYSINFO_RET_OK;
}
else
{
SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot find the specified service."));
ret = SYSINFO_RET_FAIL;
}
CloseServiceHandle(h_mgr);
return ret;
}
if (ZBX_SRV_PARAM_STATE == param_type)
{
if (0 != QueryServiceStatus(h_srv, &status))
{
for (i = 0; i < ARRSIZE(service_states) && status.dwCurrentState != service_states[i]; i++)
;
SET_UI64_RESULT(result, i);
}
else
SET_UI64_RESULT(result, 7);
}
else if (ZBX_SRV_PARAM_DESCRIPTION == param_type)
{
QueryServiceConfig2(h_srv, SERVICE_CONFIG_DESCRIPTION, NULL, 0, &sz);
if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
{
SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot obtain service description: %s",
strerror_from_system(GetLastError())));
CloseServiceHandle(h_srv);
CloseServiceHandle(h_mgr);
//.........这里部分代码省略.........