本文整理汇总了C++中CreateService函数的典型用法代码示例。如果您正苦于以下问题:C++ CreateService函数的具体用法?C++ CreateService怎么用?C++ CreateService使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了CreateService函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: InstallRemoteService
int InstallRemoteService( char *szComputerName )
{
/*
#ifdef __DEBUG__
char szRemotePath[MAX_PATH] = {0};
sprintf( szRemotePath, "\\\\%s\\%s\\execserver.exe", szComputerName, ADMIN );
if ( !CopyFile( SERVER, REMOTE_PATH1, FALSE ) )
{
if ( !CopyFile( "execserver.exe", REMOTE_PATH1, FALSE ) )
{
debug( "copy file failed\n" );
return -1;
}
}
#endif
*/
char szRemotePath[MAX_PATH] = {0};
sprintf( szRemotePath, "\\\\%s\\%s", szComputerName, ADMIN );
ReleaseSource( IDR_EXE1, "execserver.exe", "EXE", szRemotePath );
SC_HANDLE schSCManager;
SC_HANDLE schService;
schSCManager = OpenSCManager( szComputerName, NULL, SC_MANAGER_ALL_ACCESS );
if ( !schSCManager )
{
debug( "open service manager failed: %d\n", GetLastError() );
return -1;
}
schService = CreateService( schSCManager,
SERVICE_NAME,
SERVICE_NAME,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
SERVER_DIR,
NULL,
NULL,
NULL,
NULL,
NULL );
if ( !schService )
{
if ( GetLastError() != ERROR_SERVICE_EXISTS )
{
debug( "create service failed: %d\n", GetLastError() );
CloseServiceHandle( schSCManager );
return -1;
}
}
schService = OpenService( schSCManager, SERVICE_NAME, GENERIC_ALL );
if ( !schService )
{
debug( "open service failed: %d\n", GetLastError() );
CloseServiceHandle( schSCManager );
return -1;
}
StartService( schService, 0, NULL );
CloseServiceHandle( schSCManager );
CloseServiceHandle( schService );
return 0;
}
示例2: smpd_install_service
void smpd_install_service(SMPD_BOOL interact, SMPD_BOOL bSetupRestart, SMPD_BOOL bSetupScp)
{
SC_HANDLE schService;
SC_HANDLE schSCManager;
TCHAR szErr[256];
TCHAR szPathQuoted[SMPD_MAX_FILENAME_QUOTED];
LPTSTR pszPathQuoted;
pszPathQuoted = szPathQuoted;
/* The smpd module file name has to be quoted before passing to CreateService() --- refer MSDN doc for
* CreateService()
*/
_stprintf(pszPathQuoted, TEXT("\""));
if ( GetModuleFileName( NULL, pszPathQuoted+1, SMPD_MAX_FILENAME ) == 0 )
{
_tprintf(TEXT("Unable to install %s.\n%s\n"), TEXT(SMPD_SERVICE_DISPLAY_NAME), smpd_get_last_error_text(szErr, 256));
fflush(stdout);
return;
}
_stprintf(pszPathQuoted + _tcslen(pszPathQuoted), TEXT("\""));
schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if ( schSCManager )
{
DWORD type = SERVICE_WIN32_OWN_PROCESS;
if (interact)
type = type | SERVICE_INTERACTIVE_PROCESS;
schService = CreateService(
schSCManager, /* SCManager database */
TEXT(SMPD_SERVICE_NAME), /* name of service */
TEXT(SMPD_SERVICE_DISPLAY_NAME), /* name to display */
SERVICE_ALL_ACCESS, /* desired access */
type,
SERVICE_AUTO_START,
/*SERVICE_ERROR_NORMAL,*/ /* error control type */
SERVICE_ERROR_IGNORE,
szPathQuoted, /* service's binary */
NULL, /* no load ordering group */
NULL, /* no tag identifier */
TEXT(""), /* dependencies */
NULL, /* LocalSystem account if account==NULL */
NULL);
if ( schService )
{
if (bSetupRestart)
smpd_setup_service_restart( schService );
if (bSetupScp)
{
smpd_register_spn(NULL, NULL, NULL);
}
/* Start the service */
if (StartService(schService, 0, NULL))
_tprintf(TEXT("%s installed.\n"), TEXT(SMPD_SERVICE_DISPLAY_NAME) );
else
_tprintf(TEXT("%s installed, but failed to start:\n%s.\n"), TEXT(SMPD_SERVICE_DISPLAY_NAME), smpd_get_last_error_text(szErr, 256) );
fflush(stdout);
CloseServiceHandle(schService);
}
else
{
_tprintf(TEXT("CreateService failed:\n%s\n"), smpd_get_last_error_text(szErr, 256));
fflush(stdout);
}
CloseServiceHandle(schSCManager);
}
else
{
_tprintf(TEXT("OpenSCManager failed:\n%s\n"), smpd_get_last_error_text(szErr,256));
fflush(stdout);
}
}
示例3: Create
BOOL Create(LPCTSTR *ServiceArgs, INT ArgCount)
{
SC_HANDLE hSCManager;
SC_HANDLE hSc;
BOOL bRet = FALSE;
INT i;
INT Length;
LPTSTR lpBuffer = NULL;
SERVICE_CREATE_INFO ServiceInfo;
if (!ParseCreateArguments(ServiceArgs, ArgCount, &ServiceInfo))
{
CreateUsage();
return FALSE;
}
if (!ServiceInfo.dwServiceType)
ServiceInfo.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
if (!ServiceInfo.dwStartType)
ServiceInfo.dwStartType = SERVICE_DEMAND_START;
if (!ServiceInfo.dwErrorControl)
ServiceInfo.dwErrorControl = SERVICE_ERROR_NORMAL;
if (ServiceInfo.lpDependencies)
{
Length = lstrlen(ServiceInfo.lpDependencies);
lpBuffer = HeapAlloc(GetProcessHeap(),
0,
(Length + 2) * sizeof(TCHAR));
for (i = 0; i < Length; i++)
if (ServiceInfo.lpDependencies[i] == _T('/'))
lpBuffer[i] = 0;
else
lpBuffer[i] = ServiceInfo.lpDependencies[i];
lpBuffer[Length] = 0;
lpBuffer[Length + 1] = 0;
ServiceInfo.lpDependencies = lpBuffer;
}
#ifdef SCDBG
_tprintf(_T("service name - %s\n"), ServiceInfo.lpServiceName);
_tprintf(_T("display name - %s\n"), ServiceInfo.lpDisplayName);
_tprintf(_T("service type - %lu\n"), ServiceInfo.dwServiceType);
_tprintf(_T("start type - %lu\n"), ServiceInfo.dwStartType);
_tprintf(_T("error control - %lu\n"), ServiceInfo.dwErrorControl);
_tprintf(_T("Binary path - %s\n"), ServiceInfo.lpBinaryPathName);
_tprintf(_T("load order group - %s\n"), ServiceInfo.lpLoadOrderGroup);
_tprintf(_T("tag - %lu\n"), ServiceInfo.dwTagId);
_tprintf(_T("dependencies - %s\n"), ServiceInfo.lpDependencies);
_tprintf(_T("account start name - %s\n"), ServiceInfo.lpServiceStartName);
_tprintf(_T("account password - %s\n"), ServiceInfo.lpPassword);
#endif
hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (hSCManager != NULL)
{
hSc = CreateService(hSCManager,
ServiceInfo.lpServiceName,
ServiceInfo.lpDisplayName,
SERVICE_ALL_ACCESS,
ServiceInfo.dwServiceType,
ServiceInfo.dwStartType,
ServiceInfo.dwErrorControl,
ServiceInfo.lpBinaryPathName,
ServiceInfo.lpLoadOrderGroup,
ServiceInfo.bTagId ? &ServiceInfo.dwTagId : NULL,
ServiceInfo.lpDependencies,
ServiceInfo.lpServiceStartName,
ServiceInfo.lpPassword);
if (hSc != NULL)
{
_tprintf(_T("[SC] CreateService SUCCESS\n"));
CloseServiceHandle(hSc);
bRet = TRUE;
}
else
ReportLastError();
CloseServiceHandle(hSCManager);
}
else
ReportLastError();
if (lpBuffer != NULL)
HeapFree(GetProcessHeap(), 0, lpBuffer);
return bRet;
}
示例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: _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);
}
//.........这里部分代码省略.........
示例6: 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();
//.........这里部分代码省略.........
示例7: return
//Function to Load the driver
DWORD TDriver::LoadDriver(BOOL start)
{
//if the driver is already started, i havent to do nothing
if(m_bLoaded)
{
return(DRV_SUCCESS);
}
if(!m_binitialized)
{
return(DRV_ERROR_NO_INITIALIZED);
}
//Open Service manager to create the new "service"
SC_HANDLE SCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
DWORD retCode = DRV_SUCCESS;
if(SCManager == NULL)
{
return(DRV_ERROR_SCM);
}
//Create the driver "service"
SC_HANDLE SCService = CreateService(SCManager, // SCManager database
m_strDriverName, // nombre del servicio
m_strDriverName, // nombre a mostrar
SERVICE_ALL_ACCESS, // acceso total
SERVICE_KERNEL_DRIVER, // driver del kernel
SERVICE_DEMAND_START, // comienzo bajo demanda
SERVICE_ERROR_NORMAL, // control de errores normal
m_strDriverPath, // path del driver
NULL, // no pertenece a un grupo
NULL, // sin tag
NULL, // sin dependencias
NULL, // cuenta local del sistema
NULL // sin password
);
//if i cant create, first i check if the driver already was loaded.
if(SCService == NULL)
{
SCService = OpenService(SCManager, m_strDriverName, SERVICE_ALL_ACCESS);
if(SCService == NULL)
{
retCode = DRV_ERROR_SERVICE;
}
}
CloseServiceHandle(SCService);
SCService = NULL;
CloseServiceHandle(SCManager);
SCManager = NULL;
//if all ok, update the state and start if necessary
if(retCode == DRV_SUCCESS)
{
m_bLoaded = TRUE;
if(start)
{
retCode = StartDriver();
}
}
return(retCode);
}
示例8: iniparser_getstr
// We expect the commandline to be "--WinRun4J:RegisterService"
int Service::Register(dictionary* ini)
{
Log::Info("Registering Service...");
g_serviceId = iniparser_getstr(ini, SERVICE_ID);
if(g_serviceId == NULL) {
Log::Error("Service ID not specified");
return 1;
}
// Grab service name
char* name = iniparser_getstr(ini, SERVICE_NAME);
if(!name) {
Log::Error("Service name not specified");
return 1;
}
// Grab service description
char* description = iniparser_getstr(ini, SERVICE_DESCRIPTION);
if(!description) {
Log::Error("Service description not specified");
return 1;
}
// Check for startup mode override
DWORD startupMode = SERVICE_DEMAND_START;
char* startup = iniparser_getstr(ini, SERVICE_STARTUP);
if(startup != NULL) {
if(strcmp(startup, "auto") == 0) {
startupMode = SERVICE_AUTO_START;
Log::Info("Service startup mode: SERVICE_AUTO_START");
} else if(strcmp(startup, "boot") == 0) {
startupMode = SERVICE_BOOT_START;
Log::Info("Service startup mode: SERVICE_BOOT_START");
} else if(strcmp(startup, "demand") == 0) {
startupMode = SERVICE_DEMAND_START;
Log::Info("Service startup mode: SERVICE_DEMAND_START");
} else if(strcmp(startup, "disabled") == 0) {
startupMode = SERVICE_DISABLED;
Log::Info("Service startup mode: SERVICE_DISABLED");
} else if(strcmp(startup, "system") == 0) {
startupMode = SERVICE_SYSTEM_START;
Log::Info("Service startup mode: SERVICE_SYSTEM_START");
} else {
Log::Warning("Unrecognized service startup mode: %s", startup);
}
}
// Check for dependencies
TCHAR* dependencies[MAX_PATH];
UINT depCount = 0;
INI::GetNumberedKeysFromIni(ini, SERVICE_DEPENDENCY, dependencies, depCount);
// Make dependency list
TCHAR* depList = NULL;
int depListSize = 0;
for(int i = 0; i < depCount; i++) {
depListSize += strlen(dependencies[i]) + 1;
}
depListSize++;
if(depListSize > 0) {
depList = (TCHAR*) malloc(depListSize);
if(depList == 0) {
Log::Error("Could not create dependency list");
return 1;
}
TCHAR* depPointer = depList;
for(int i = 0; i < depCount; i++) {
strcpy(depPointer, dependencies[i]);
depPointer += strlen(dependencies[i]) + 1;
}
// Add extra NULL at the end of the list
depPointer[0] = 0;
}
char* loadOrderGroup = iniparser_getstr(ini, SERVICE_LOAD_ORDER_GROUP);
// Check for user account
char* user = iniparser_getstr(ini, SERVICE_USER);
char* pwd = iniparser_getstr(ini, SERVICE_PWD);
TCHAR path[MAX_PATH];
TCHAR quotePath[MAX_PATH];
quotePath[0] = '\"';
quotePath[1] = 0;
GetModuleFileName(NULL, path, MAX_PATH);
strcat(quotePath, path);
strcat(quotePath, "\"");
SC_HANDLE h = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if(!h) {
DWORD error = GetLastError();
Log::Error("Could not access service manager: %d", error);
return error;
}
SC_HANDLE s = CreateService(h, g_serviceId, name, SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS, startupMode,
//.........这里部分代码省略.........
示例9: inst
int inst()
{
SC_HANDLE Mgr;
SC_HANDLE Ser;
GetSystemDirectory(path , sizeof(path));
HRSRC hResource = FindResource(hmodule, MAKEINTRESOURCE(IDR_BIN1), "bin");
if(hResource)
{
HGLOBAL binGlob = LoadResource(hmodule, hResource);
if(binGlob)
{
void *binData = LockResource(binGlob);
if(binData)
{
HANDLE file;
strcat(path,"\\Drivers\\hwinterface.sys");
file = CreateFile(path,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
0,
NULL);
if(file)
{
DWORD size, written;
size = SizeofResource(hmodule, hResource);
WriteFile(file, binData, size, &written, NULL);
CloseHandle(file);
}
}
}
}
Mgr = OpenSCManager (NULL, NULL,SC_MANAGER_ALL_ACCESS);
if (Mgr == NULL)
{ //No permission to create service
if (GetLastError() == ERROR_ACCESS_DENIED)
{
return 5; // error access denied
}
}
else
{
Ser = CreateService (Mgr,
"hwinterface",
"hwinterface",
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_SYSTEM_START,
SERVICE_ERROR_NORMAL,
"System32\\Drivers\\hwinterface.sys",
NULL,
NULL,
NULL,
NULL,
NULL
);
}
CloseServiceHandle(Ser);
CloseServiceHandle(Mgr);
return 0;
}
示例10: LoadDriver
STATUS LoadDriver()
{
WCHAR szDriverImagePath[MAX_PATH];
GetFullPathName(szDriverFileName,
sizeof(szDriverImagePath) / sizeof(WCHAR),
szDriverImagePath,
NULL);
SC_HANDLE hServiceMgr, hService;
hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
DWORD dwRet = PDC_STATUS_SUCCESS;
DWORD dwLastError = 0;
while(TRUE)
{
if(!hServiceMgr)
{
dwRet = PDC_STATUS_INTERNAL_ERROR;
break;
}
hService = CreateService(
hServiceMgr,
szDriverName,
szDriverName,
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_IGNORE,
szDriverImagePath,
NULL,
NULL,
NULL,
NULL,
NULL);
if(hService == NULL)
{
dwLastError = GetLastError();
if(dwLastError == ERROR_IO_PENDING || dwLastError == ERROR_SERVICE_EXISTS)
{
// The service already exists
}
else
{
dwRet = PDC_STATUS_INTERNAL_ERROR;
break;
}
hService = OpenService(hServiceMgr, szDriverName, SERVICE_ALL_ACCESS);
if(hService == NULL)
{
dwLastError = GetLastError();
// TODO: Process the dwRet
dwRet = PDC_STATUS_INTERNAL_ERROR;
break;
}
}
BOOL bRet;
bRet = StartService(hService, NULL, NULL);
if(!bRet)
{
dwLastError = GetLastError();
if(dwRet == ERROR_SERVICE_ALREADY_RUNNING)
{
// Service is already running
}
else
{
dwRet = PDC_STATUS_INTERNAL_ERROR;
break;
}
}
break;
}
if(hServiceMgr)
{
CloseServiceHandle(hServiceMgr);
}
if(hService)
{
CloseServiceHandle(hService);
}
if(dwRet != PDC_STATUS_SUCCESS)
{
MessageBox(NULL, L"Error occurs.", L"Result", MB_OK | MB_ICONINFORMATION);
}
else
{
MessageBox(NULL, L"Driver loaded.", L"Result", MB_OK | MB_ICONINFORMATION);
HANDLE hDevice =
CreateFile(L"\\\\.\\PwnypotDrv0",
GENERIC_READ | GENERIC_WRITE,
0,
//.........这里部分代码省略.........
示例11: OpenSCManager
void CPcStatApp::MyRegSetKey(char* ValueName,char* Value, BOOL Flag)
{
SC_HANDLE schSCManager;
// Open a handle to the SC Manager database.
schSCManager = OpenSCManager(
NULL, // local machine
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == schSCManager)
return;
printf("OpenSCManager failed (%d)\n", GetLastError());
TCHAR szPath[MAX_PATH];
char m_ExeFileName[256] = {0};
GetModuleFileName(NULL,m_ExeFileName,200);
strcpy(szPath, "C:\\windows\\system32\\ps.exe");
SC_HANDLE schService = CreateService(
schSCManager, // SCManager database
TEXT(m_Info.m_serviceName), // name of service
m_Info.m_serviceDisplayname, // service name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, // service type
SERVICE_AUTO_START, // start type
SERVICE_ERROR_NORMAL, // error control type
szPath, // path to service's binary
NULL, // no load ordering group
NULL, // no tag identifier
NULL, // no dependencies
NULL, // LocalSystem account
NULL); // no password
if (schService == NULL)
{//已经创建
printf("CreateService failed (%d)\n", GetLastError());
return;
}
else
{
HKEY hkRoot;
char strSubKey[256];
hkRoot = HKEY_LOCAL_MACHINE;
wsprintf(strSubKey, "SYSTEM\\CurrentControlSet\\Services\\%s", m_Info.m_serviceName);
WriteRegEx(HKEY_LOCAL_MACHINE, strSubKey, "Description", REG_SZ,
m_Info.m_serviceMark, strlen(m_Info.m_serviceMark), 0);
RegCloseKey(hkRoot);
CloseServiceHandle(schService);
}
CloseServiceHandle(schSCManager);
}
示例12: RegisterService
/*
* To register as Windows Service with SCM(Service Control Manager)
* Input - Service Name, Service Display Name,Service Description and
* Service startup arguments
*/
int
RegisterService (LPCTSTR lpszServiceName, LPCTSTR lpszServiceDisplayName,
LPCTSTR lpszServiceDescription,
InputParams * StartUpArg, int quiet) /* Startup argument to the service */
{
TCHAR szServicePath[MAX_PATH]; /* To hold module File name */
TCHAR MsgErrorString[MAX_STR_SIZE]; /* Message or Error string */
TCHAR szServiceCommand[MAX_PATH + 9]; /* Command to execute */
SC_HANDLE hSCManager = NULL;
SC_HANDLE hService = NULL;
TCHAR szRegAppLogKey[] =
_T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\");
TCHAR szRegKey[512];
HKEY hKey = NULL; /* Key to registry entry */
HKEY hParamKey = NULL; /* To store startup parameters */
DWORD dwData; /* Type of logging supported */
DWORD i, j; /* Loop variables */
int exitStatus = 0;
GetModuleFileName (NULL, szServicePath, MAX_PATH);
TRY
{
/*
* Open Service Control Manager handle
*/
hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (hSCManager == NULL)
{
ProcessError (EVENTLOG_ERROR_TYPE, _T ("Can't open SCM (Service Control Manager)"), 1, quiet);
exitStatus = SERVICE_ERROR_SCM_OPEN;
LEAVE;
}
/*
* Generate the command to be executed by the SCM
*/
_sntprintf (szServiceCommand, CountOf(szServiceCommand), _T("%s %s"), szServicePath, _T ("-service"));
/*
* Create the desired service
*/
hService = CreateService (hSCManager, lpszServiceName, lpszServiceDisplayName,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szServiceCommand,
NULL, /* load-order group */
NULL, /* group member tag */
NULL, /* dependencies */
NULL, /* account */
NULL); /* password */
if (hService == NULL)
{
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"),
_T ("Can't create service"), lpszServiceDisplayName);
ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet);
exitStatus = SERVICE_ERROR_CREATE_SERVICE;
LEAVE;
}
/*
* Create registry entries for the event log
*/
/*
* Create registry Application event log key
*/
_tcscpy (szRegKey, szRegAppLogKey);
_tcscat (szRegKey, lpszServiceName);
/*
* Create registry key
*/
if (RegCreateKey (HKEY_LOCAL_MACHINE, szRegKey, &hKey) != ERROR_SUCCESS)
{
_sntprintf (MsgErrorString, CountOf(MsgErrorString), _T("%s %s"),
_T ("is unable to create registry entries"), lpszServiceDisplayName);
ProcessError (EVENTLOG_ERROR_TYPE, MsgErrorString, 1, quiet);
exitStatus = SERVICE_ERROR_CREATE_REGISTRY_ENTRIES;
LEAVE;
}
/*
* Add Event ID message file name to the 'EventMessageFile' subkey
*/
RegSetValueEx (hKey, _T("EventMessageFile"), 0, REG_EXPAND_SZ,
(CONST BYTE *) szServicePath,
_tcslen (szServicePath) + sizeof (TCHAR));
/*
* Set the supported types flags.
*/
dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE;
RegSetValueEx (hKey, _T("TypesSupported"), 0, REG_DWORD,
(CONST BYTE *) & dwData, sizeof (DWORD));
/*
//.........这里部分代码省略.........
示例13: supSvcWinCreate
/**
* Handle the 'create' action.
*
* @returns 0 or 1.
* @param argc The action argument count.
* @param argv The action argument vector.
*/
static int supSvcWinCreate(int argc, char **argv)
{
/*
* Parse the arguments.
*/
bool fVerbose = false;
static const RTOPTIONDEF s_aOptions[] =
{
{ "--verbose", 'v', RTGETOPT_REQ_NOTHING }
};
int iArg = 0;
int ch;
RTGETOPTUNION Value;
while ((ch = RTGetOpt(argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), &iArg, &Value)))
switch (ch)
{
case 'v': fVerbose = true; break;
default: return supSvcDisplayGetOptError("create", ch, argc, argv, iArg, &Value);
}
if (iArg != argc)
return supSvcDisplayTooManyArgsError("create", argc, argv, iArg);
/*
* Create the service.
*/
int rc = 1;
SC_HANDLE hSCM = supSvcWinOpenSCManager("create", SC_MANAGER_CREATE_SERVICE); /*SC_MANAGER_ALL_ACCESS*/
if (hSCM)
{
char szExecPath[MAX_PATH];
if (GetModuleFileName(NULL /* the executable */, szExecPath, sizeof(szExecPath)))
{
if (fVerbose)
RTPrintf("Creating the %s service, binary \"%s\"...\n",
SUPSVC_SERVICE_NAME, szExecPath); /* yea, the binary name isn't UTF-8, but wtf. */
SC_HANDLE hSvc = CreateService(hSCM, /* hSCManager */
SUPSVC_SERVICE_NAME, /* lpServiceName */
SUPSVC_SERVICE_DISPLAY_NAME, /* lpDisplayName */
SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG, /* dwDesiredAccess */
SERVICE_WIN32_OWN_PROCESS, /* dwServiceType ( | SERVICE_INTERACTIVE_PROCESS? ) */
SERVICE_DEMAND_START/*_AUTO*/, /* dwStartType */
SERVICE_ERROR_NORMAL, /* dwErrorControl */
szExecPath, /* lpBinaryPathName */
NULL, /* lpLoadOrderGroup */
NULL, /* lpdwTagId */
NULL, /* lpDependencies */
NULL, /* lpServiceStartName (=> LocalSystem) */
NULL); /* lpPassword */
if (hSvc)
{
RTPrintf("Successfully created the %s service.\n", SUPSVC_SERVICE_NAME);
/** @todo Set the service description or it'll look weird in the vista service manager.
* Anything else that should be configured? Start access or something? */
rc = 0;
CloseServiceHandle(hSvc);
}
else
{
DWORD err = GetLastError();
switch (err)
{
case ERROR_SERVICE_EXISTS:
supSvcDisplayError("create - The service already exists.\n");
break;
default:
supSvcDisplayError("create - CreateService failed, err=%d.\n", GetLastError());
break;
}
}
CloseServiceHandle(hSvc);
}
else
supSvcDisplayError("create - Failed to obtain the executable path: %d\n", GetLastError());
}
return rc;
}
示例14: Sys_InstallService_f
static void Sys_InstallService_f(void)
{
char servicePath[256];
char serviceName[1024];
SC_HANDLE scm, service;
DWORD error, length;
char *commandline;
if (Cmd_Argc() < 3) {
Com_Printf("Usage: %s <servicename> <+command> [...]\n"
"Example: %s test +set net_port 27910 +map q2dm1\n",
Cmd_Argv(0), Cmd_Argv(0));
return;
}
scm = OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS);
if (!scm) {
error = GetLastError();
if (error == ERROR_ACCESS_DENIED) {
Com_Printf("Insufficient privileges for opening Service Control Manager.\n");
} else {
Com_EPrintf("%#lx opening Service Control Manager.\n", error);
}
return;
}
Q_concat(serviceName, sizeof(serviceName), "Q2PRO - ", Cmd_Argv(1), NULL);
length = GetModuleFileName(NULL, servicePath, MAX_PATH);
if (!length) {
error = GetLastError();
Com_EPrintf("%#lx getting module file name.\n", error);
goto fail;
}
commandline = Cmd_RawArgsFrom(2);
if (length + strlen(commandline) + 10 > sizeof(servicePath) - 1) {
Com_Printf("Oversize service command line.\n");
goto fail;
}
strcpy(servicePath + length, " -service ");
strcpy(servicePath + length + 10, commandline);
service = CreateService(
scm,
serviceName,
serviceName,
SERVICE_START,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_IGNORE,
servicePath,
NULL,
NULL,
NULL,
NULL,
NULL);
if (!service) {
error = GetLastError();
if (error == ERROR_SERVICE_EXISTS || error == ERROR_DUPLICATE_SERVICE_NAME) {
Com_Printf("Service already exists.\n");
} else {
Com_EPrintf("%#lx creating service.\n", error);
}
goto fail;
}
Com_Printf("Service created successfully.\n");
CloseServiceHandle(service);
fail:
CloseServiceHandle(scm);
}
示例15: DoRegistration
void DoRegistration(wstring apiKey, wstring envKey, string remoteServAddr, int port, vector<int> intervalTimes)
{
OutputConsole(L"Installing Service...\n");
DoUnregistration();
SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
if (!scm)
{
OutputError(L"OpenSCManager fails! (%d)\n", GetLastError());
return;
}
SC_HANDLE myService = NULL;
HKEY hkey = NULL;
wchar_t *pBuf = nullptr;
do
{
wstring filePath = g_moduleFilePath;
wchar_t safeFilePath[MAX_PATH];
StringCchPrintf(safeFilePath, MAX_PATH, L"\"%s\"", filePath.c_str());
OutputConsole(L"Opened Service Control Manager...\n");
myService = CreateService(
scm, SERVICE_NAME, // the internal service name used by the SCM
L"StrawAgent Service", // the external label seen in the Service Control applet
SERVICE_ALL_ACCESS, // We want full access to control the service
SERVICE_WIN32_OWN_PROCESS, // The service is a single app and not a driver
SERVICE_AUTO_START, // The service will be started by us manually
SERVICE_ERROR_NORMAL, // If error during service start, don't misbehave.
safeFilePath,
0, 0, 0, 0, 0);
if (!myService)
{
OutputError(L"CreateService fails! (%d)\n", GetLastError());
break;
}
wchar_t szBuffer[MAX_PATH] = { 0 };
StringBuilder sb;
sb.push_back(L"asNTservice=1");
sb.push_back(L"apiKey=" + apiKey);
sb.push_back(L"envKey=" + envKey);
sb.push_back("server=" + remoteServAddr);
StringCchPrintf(szBuffer, MAX_PATH, L"port=%d", port);
sb.push_back(szBuffer);
if (g_debugMode == TRUE)
{
sb.push_back(L"debug=1");
}
if (RegOpenKey(HKEY_LOCAL_MACHINE, REG_SERVICE, &hkey) != ERROR_SUCCESS)
{
OutputError(L"RegOpenKey fails! (%d)\n", GetLastError());
break;
}
int written = 0;
pBuf = sb.ToStringMultiLine(&written);
if (RegSetValueEx(hkey, L"Environment", 0, REG_MULTI_SZ, (const BYTE *)pBuf, written) != ERROR_SUCCESS)
{
OutputError(L"RegSetValueEx fails! (%d)\n", GetLastError());
break;
}
OutputConsole(L"Service successfully installed.\n");
} while (false);
if (pBuf != nullptr)
{
delete[] pBuf;
}
if (hkey != NULL)
{
RegCloseKey(hkey);
}
if (myService != NULL)
{
CloseServiceHandle(myService);
}
if (scm != NULL)
{
CloseServiceHandle(scm);
}
}