1、

#include <stdio.h>
#include <Windows.h>
#include <tchar.h> #include <process.h> TCHAR szServiceName[] = _T("MyTestService");
DWORD dwThreadID;
HANDLE hEvent = INVALID_HANDLE_VALUE;
SERVICE_STATUS status;
SERVICE_STATUS_HANDLE hServiceStatus; void Init();
BOOL IsServiceInstalled();
BOOL InstallService();
BOOL UninstallService();
BOOL ServiceCtrlStart();
BOOL ServiceCtrlStop();
void WINAPI ServiceMain();
void WINAPI ServiceStrl(DWORD dwOpcode);
void LogEvent(LPCTSTR pszFormat, ...); //Usuage
// Install service:
//TestService.exe /install
// Uninstall service:
//TestService.exe /uninstall
// Start service:
//TestService.exe /start
// Stop service:
//TestService.exe /stop int main( int argc, char* argv[] )
{
Init(); dwThreadID = ::GetCurrentThreadId(); SERVICE_TABLE_ENTRY st[] =
{
{ szServiceName, (LPSERVICE_MAIN_FUNCTION)ServiceMain },
{ NULL, NULL }
}; LPSTR lpCmdLine = argv[]; if ( argc == )
{
BOOL bRet; if (stricmp(lpCmdLine, "/install") == )
{
bRet = InstallService();
if ( bRet == TRUE )
{
printf( "Install service %s success", szServiceName );
}else
{
printf( "Install service %s failed", szServiceName );
}
}
else if (stricmp(lpCmdLine, "/uninstall") == )
{
bRet = UninstallService();
if ( bRet == TRUE )
{
printf( "Uninstall service %s success", szServiceName );
}
else
{
printf( "Uninstall service %s failed", szServiceName );
}
}
else if (stricmp(lpCmdLine, "/start") == )
{
bRet = ServiceCtrlStart();
if ( bRet == TRUE )
{
printf( "Start service %s success", szServiceName );
}else
{
printf( "Start service %s failed", szServiceName );
}
}
else if (stricmp(lpCmdLine, "/stop") == )
{
bRet = ServiceCtrlStop();
if ( bRet == TRUE )
{
printf( "Stop service %s success", szServiceName );
}
else
{
printf( "Stop service %s failed", szServiceName );
}
}
else
{
if (!::StartServiceCtrlDispatcher(st))
{
LogEvent(_T("Register Service Main Function Error!"));
}
}
}
else
{
if (!::StartServiceCtrlDispatcher(st))
{
LogEvent(_T("Register Service Main Function Error!"));
}
}
return ;
} //初始化相关结构
void Init()
{
hServiceStatus = NULL;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
status.dwCurrentState = SERVICE_STOPPED;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
status.dwWin32ExitCode = ;
status.dwServiceSpecificExitCode = ;
status.dwCheckPoint = ;
status.dwWaitHint = ;
} void SubThread(void *_pParam)
{
LogEvent(_T("SubThread - 1"));
Sleep( * );
LogEvent(_T("SubThread - 2"));
_endthread();
} //服务主线程函数,既用户选择开启服务时调用的函数
void WINAPI ServiceMain()
{
// Register the control request handler
status.dwCurrentState = SERVICE_START_PENDING;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP; LogEvent(_T("ServiceMain")); //注册服务控制
hServiceStatus = RegisterServiceCtrlHandler(szServiceName, ServiceStrl);
if (hServiceStatus == NULL)
{
LogEvent(_T("Handler not installed"));
return;
}
SetServiceStatus(hServiceStatus, &status); //如下代码可以为启动服务前的准备工作
hEvent = ::CreateEvent( NULL, TRUE, FALSE, NULL );
if ( hEvent == NULL )
{
status.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(hServiceStatus, &status);
LogEvent(_T("Failure to start service"));
return;
}
// //更改服务状态为启动
status.dwWin32ExitCode = S_OK;
status.dwCheckPoint = ;
status.dwWaitHint = ;
status.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(hServiceStatus, &status); {
_beginthread( SubThread, , NULL );
} //等待用户选择停止服务,
//当然你也可以把你的服务代码用线程来执行,
//此时这里只需等待线程结束既可。
while ( WaitForSingleObject( hEvent, ) != WAIT_OBJECT_0 )
{
//模拟服务的运行,应用时将主要任务放于此即可
LogEvent(_T("Service runing..."));
}
// //停止服务
status.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(hServiceStatus, &status);
LogEvent(_T("Service stopped"));
} //服务控制函数
void WINAPI ServiceStrl(DWORD dwOpcode)
{
switch (dwOpcode)
{
case SERVICE_CONTROL_STOP:
status.dwCurrentState = SERVICE_STOP_PENDING;
SetServiceStatus(hServiceStatus, &status);
//告诉服务线程停止工作
::SetEvent( hEvent );
LogEvent(_T("want to stopped Service"));
break;
case SERVICE_CONTROL_PAUSE:
break;
case SERVICE_CONTROL_CONTINUE:
break;
case SERVICE_CONTROL_INTERROGATE:
break;
case SERVICE_CONTROL_SHUTDOWN:
break;
default:
LogEvent(_T("Bad service request"));
}
} //判断服务是否已安装
BOOL IsServiceInstalled()
{
BOOL bResult = FALSE; //打开服务控制管理器
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hSCM != NULL)
{
//打开服务
SC_HANDLE hService = ::OpenService(hSCM, szServiceName, SERVICE_QUERY_CONFIG);
if (hService != NULL)
{
bResult = TRUE;
::CloseServiceHandle(hService);
}
::CloseServiceHandle(hSCM);
}
return bResult;
} //安装服务
BOOL InstallService()
{
if (IsServiceInstalled())
{
return TRUE;
} //打开服务控制管理器
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
{
return FALSE;
} // Get the executable file path
TCHAR szFilePath[MAX_PATH];
::GetModuleFileName(NULL, szFilePath, MAX_PATH); //创建服务
SC_HANDLE hService = ::CreateService(
hSCM,
szServiceName,
szServiceName,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, //如果为SERVICE_DEMAND_START则表示此服务需手工启动
SERVICE_ERROR_NORMAL,
szFilePath,
NULL,
NULL,
_T(""),
NULL,
NULL); if (hService == NULL)
{
::CloseServiceHandle(hSCM);
return FALSE;
} ::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM);
return TRUE;
} //删除服务
BOOL UninstallService()
{
if (!IsServiceInstalled())
{
return TRUE;
}
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
{
return FALSE;
} SC_HANDLE hService = ::OpenService(hSCM, szServiceName, SERVICE_STOP | DELETE);
if (hService == NULL)
{
::CloseServiceHandle(hSCM);
return FALSE;
}
SERVICE_STATUS status;
::ControlService(hService, SERVICE_CONTROL_STOP, &status); //删除服务
BOOL bDelete = ::DeleteService(hService);
::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM); if (bDelete)
{
return TRUE;
} LogEvent(_T("Service could not be deleted"));
return FALSE;
} //开启服务
BOOL ServiceCtrlStart()
{
BOOL bRet;
SC_HANDLE hSCM;
SC_HANDLE hService; hSCM=OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
if (hSCM!=NULL)
{
hService=OpenService( hSCM, szServiceName, SERVICE_START);
if (hService!=NULL)
{
//开始Service
bRet = StartService(hService,,NULL);
CloseServiceHandle(hService);
}else
{
bRet = FALSE;
}
CloseServiceHandle(hSCM);
}
else
{
bRet = FALSE;
}
return bRet;
} //停止服务
BOOL ServiceCtrlStop()
{
BOOL bRet;
SC_HANDLE hSCM;
SC_HANDLE hService;
SERVICE_STATUS ServiceStatus; hSCM=OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );
if (hSCM!=NULL)
{
hService=OpenService( hSCM, szServiceName, SERVICE_STOP|SERVICE_QUERY_STATUS );
if (hService!=NULL)
{
QueryServiceStatus( hService, &ServiceStatus );
if (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
{
bRet = ControlService( hService, SERVICE_CONTROL_STOP, &ServiceStatus );
}
else
{
bRet = FALSE;
}
CloseServiceHandle( hService );
}
else
{
bRet = FALSE;
}
CloseServiceHandle( hSCM );
}
else
{
bRet = FALSE;
}
return bRet;
} //记录日记
void LogEvent(LPCTSTR pFormat, ...)
{
TCHAR chMsg[];
HANDLE hEventSource;
LPTSTR lpszStrings[];
va_list pArg; va_start(pArg, pFormat);
_vstprintf(chMsg, pFormat, pArg);
va_end(pArg); lpszStrings[] = chMsg; hEventSource = RegisterEventSource(NULL, szServiceName);
if (hEventSource != NULL)
{
ReportEvent(hEventSource, EVENTLOG_INFORMATION_TYPE, , , NULL, , , (LPCTSTR*) &lpszStrings[], NULL);
DeregisterEventSource(hEventSource);
}
}

2、CreateProcess

http://www.jb51.net/article/66511.htm

3、

Windows服务程序_测试01的更多相关文章

  1. .NET 跨平台RPC框架DotNettyRPC Web后台快速开发框架(.NET Core) EasyWcf------无需配置,无需引用,动态绑定,轻松使用 C# .NET 0配置使用Wcf(半成品) C# .NET Socket 简单实用框架 C# .NET 0命令行安装Windows服务程序

    .NET 跨平台RPC框架DotNettyRPC   DotNettyRPC 1.简介 DotNettyRPC是一个基于DotNetty的跨平台RPC框架,支持.NET45以及.NET Standar ...

  2. C#写Windows Service(windows服务程序)

    背景:        要学习使用一个新东西,我们必须知道他是个什么东西.对于我们此次研究的windows服务来说,他又是个什么东西,其实也没有什么高深的了. windows service概述: 一个 ...

  3. .net Windows服务程序和安装程序制作图解 及 VS 2010创建、安装、调试 windows服务(windows service)

    .net Windows服务程序和安装程序制作 最近项目中用到window服务程序,以前没接触过,比较陌生,花了两天的时间学习了下,写了个简单的服务,但在制作安装程序的时候,参照网上很多资料,却都制作 ...

  4. 用Visual C#创建Windows服务程序

    一.Windows服务介绍: Windows服务以前被称作NT服务,是一些运行在Windows NT.Windows 2000和Windows XP等操作系统下用户环境以外的程序.在以前,编写Wind ...

  5. 用C/C++创建windows服务程序

    转载:https://blog.csdn.net/chenyujing1234/article/details/8023816 一.演示过程下方代码演示了如何使用vs(C/C++)创建windows服 ...

  6. Redis windows版安装测试

    1.下载 下载地址是 https://github.com/microsoftarchive/redis/releases/tag/win-3.2.100 ,我选择的是Redis-x64-3.2.10 ...

  7. WCF学习之旅—WCF服务的Windows 服务程序寄宿(十一)

    上接    WCF学习之旅—WCF服务部署到IIS7.5(九) WCF学习之旅—WCF服务部署到应用程序(十) 七 WCF服务的Windows 服务程序寄宿 这种方式的服务寄宿,和IIS一样有一个一样 ...

  8. 关于开发Windows服务程序容易搞混的地方!

    在开发Windows服务程序时,我们一般需要添加安装程序,即:serviceInstaller,里面有几个关于名称属性,你都搞明白了吗? 1.Description:表示服务说明(描述服务是干什么的) ...

  9. Windows服务程序和安装程序制作

    转:http://www.cr173.com/html/15350_1.html 本文介绍了如何用C#创建.安装.启动.监控.卸载简单的Windows Service 的内容步骤和注意事项. 一.创建 ...

随机推荐

  1. 电力项目十七--数据字典首页JS添加和删除表格

    知识点:jQuery是一个JavaScript函数库. JS代码: function insertRows(){ //获取表格对象 var tb1 = $("#dictTbl"); ...

  2. SSH电力项目四-显示首页

    1.登录页面: 将上一节中的页面放到/WEB-INF/page/目录下,需要登录后才能访问该页面: 对应页面:/WEB-INF/page/menu/home.jsp <%@ page langu ...

  3. 微信小程序 --- Image组件

    Image组件可以在小程序中展示图片,支持外链. Image组件可以调用API,进行三种缩放,九种裁剪. Image组件有默认值:300*225 属性: src:图片资源地址. mode:图片裁剪缩放 ...

  4. mongdb ---shard

    http://blog.fens.me/mongodb-shard/ https://segmentfault.com/a/1190000004263332 1. 和用户管理相关的操作基本都要在adm ...

  5. JSON_CONTAINS

    select * from tb    where info->'$.name' = '特价促销'  or JSON_CONTAINS(info->'$[*].name', '" ...

  6. 【css a标签 鼠标悬浮时变手型】

    <a href="#" style="cursor:pointer">

  7. 利用阿里云搭建私有Git服务器

    服务器系统:Centos 6 (查看centos版本命令:lsb_release -a) 客户端系统:Windows 7 一.服务器端安装Git ==通常centos上使用yum源安装的git版本过低 ...

  8. Django中URL的解析和反查

    add by zhj: 如果想用reverse(namespace1:namespace2:...:namespaceN:name)反查url(注意:用reverse('polls:index')方法 ...

  9. day15(Mysql学习)

      day15-MySQL   数据库   1 数据库概念(了解) 1.1 什么是数据库 数据库就是用来存储和管理数据的仓库! 数据库存储数据的优先: 可存储大量数据: 方便检索: 保持数据的一致性. ...

  10. Codeforces Round #526 (Div. 2) Solution

    A. The Fair Nut and Elevator Solved. 签. #include <bits/stdc++.h> using namespace std; #define ...