Windows服务程序_测试01
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的更多相关文章
- .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 ...
- C#写Windows Service(windows服务程序)
背景: 要学习使用一个新东西,我们必须知道他是个什么东西.对于我们此次研究的windows服务来说,他又是个什么东西,其实也没有什么高深的了. windows service概述: 一个 ...
- .net Windows服务程序和安装程序制作图解 及 VS 2010创建、安装、调试 windows服务(windows service)
.net Windows服务程序和安装程序制作 最近项目中用到window服务程序,以前没接触过,比较陌生,花了两天的时间学习了下,写了个简单的服务,但在制作安装程序的时候,参照网上很多资料,却都制作 ...
- 用Visual C#创建Windows服务程序
一.Windows服务介绍: Windows服务以前被称作NT服务,是一些运行在Windows NT.Windows 2000和Windows XP等操作系统下用户环境以外的程序.在以前,编写Wind ...
- 用C/C++创建windows服务程序
转载:https://blog.csdn.net/chenyujing1234/article/details/8023816 一.演示过程下方代码演示了如何使用vs(C/C++)创建windows服 ...
- Redis windows版安装测试
1.下载 下载地址是 https://github.com/microsoftarchive/redis/releases/tag/win-3.2.100 ,我选择的是Redis-x64-3.2.10 ...
- WCF学习之旅—WCF服务的Windows 服务程序寄宿(十一)
上接 WCF学习之旅—WCF服务部署到IIS7.5(九) WCF学习之旅—WCF服务部署到应用程序(十) 七 WCF服务的Windows 服务程序寄宿 这种方式的服务寄宿,和IIS一样有一个一样 ...
- 关于开发Windows服务程序容易搞混的地方!
在开发Windows服务程序时,我们一般需要添加安装程序,即:serviceInstaller,里面有几个关于名称属性,你都搞明白了吗? 1.Description:表示服务说明(描述服务是干什么的) ...
- Windows服务程序和安装程序制作
转:http://www.cr173.com/html/15350_1.html 本文介绍了如何用C#创建.安装.启动.监控.卸载简单的Windows Service 的内容步骤和注意事项. 一.创建 ...
随机推荐
- hdu4975 网络流解方程组(网络流+dfs判环或矩阵DP)
http://acm.hdu.edu.cn/showproblem.php?pid=4975 A simple Gaussian elimination problem. Time Limit: 20 ...
- U盘安装Win7系统,遇到硬盘鼠标键盘失灵等情况,如何安装U盘中加入USB3.0驱动的支持
U盘安装系统出现鼠标键盘不能使用,在intel六代处理器平台,安装过程中会出现安装原生镜像不能识别或者鼠标键盘不能使用等情况,可以参考以下方法进行. 风险提示:重装或升级系统会导致系统盘数据丢失,建议 ...
- Windows系统下做定时任务为Oracle数据库每天自动备份
1.创建备份目录d:\backup, 创建批处理命令Bak.bat,编写备份脚本 ? 1 2 exp user/passwd@orcl DIRECT=Y BUFFER=100000 FILE=D:\b ...
- 【转】SQL Server编程游标
在关系数据库中,我们对于查询的思考是面向集合的.而游标打破了这一规则,游标使得我们思考方式变为逐行进行.对于类C的开发人员来着,这样的思考方式会更加舒服. 正常面向集合的思维方式是: 而对于游标来说: ...
- HDU 4238 You Are the One
You Are the One Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Tot ...
- beans有无状态
Spring Bean Scopes https://www.tutorialspoint.com/spring/spring_bean_scopes.htm When defining a < ...
- JavaScript如何把字符串中每个单词首字母转化为大写
先上代码,再做解释. 思路分析: 1. 首先先把字符串中的单词转化为小写(toLowerCase),再对其进行截取(split),截取依据为按照空格截取: 2. 此时经过步骤一之后得到的东西是一个数组 ...
- openstack配置域名访问
#openstack配置域名访问 openstack pike 安装 目录汇总 http://www.cnblogs.com/elvi/p/7613861.html #主要是在默认配置的基础上,做了个 ...
- 洛谷P3939 数颜色 二分查找
正解:二分 解题报告: 传送门! 话说其实我开始看到这题想到的是分块,,, 但是显然不用这么复杂,,,因为仔细看下这题,会发现每次只改变相邻的兔子的位置 所以开个vector(或者开个数组也成QwQ( ...
- 人人网张铁安:Feed系统架构分析(转)
原文:http://www.csdn.net/article/2010-07-26/277273 继成功举办首期TUP活动后,日前在北京丽亭华苑酒店鸿运二厅,由CSDN和<程序员> 杂志联 ...