摘自 http://blog.youkuaiyun.com/fin86889003/article/details/26255387
微软的项目模板能很好的支持WINDOWS服务开发,如C#的windows服务项目
C++开发的话,也不难,使用一些API就能实现,下附代码
- #include "stdafx.h"
- #include "Windows.h"
-
- #define SERVICE_NAME "srv_demo"
-
- SERVICE_STATUS ServiceStatus;
- SERVICE_STATUS_HANDLE hServiceStatusHandle;
- void WINAPI service_main(int argc, char** argv);
- void WINAPI ServiceHandler(DWORD fdwControl);
-
- TCHAR szSvcName[80];
- SC_HANDLE schSCManager;
- SC_HANDLE schService;
- int uaquit;
- FILE* log;
-
- DWORD WINAPI srv_core_thread(LPVOID para)
- {
- int i = 0;
- for(;;)
- {
- if(uaquit)
- {
- break;
- }
- fprintf(log,"srv_core_thread run time count:%d\n",i++);
- Sleep(5000);
- }
- return NULL;
- }
-
-
- void WINAPI ServiceHandler(DWORD fdwControl)
- {
- switch(fdwControl)
- {
- case SERVICE_CONTROL_STOP:
- case SERVICE_CONTROL_SHUTDOWN:
- ServiceStatus.dwWin32ExitCode = 0;
- ServiceStatus.dwCurrentState = SERVICE_STOPPED;
- ServiceStatus.dwCheckPoint = 0;
- ServiceStatus.dwWaitHint = 0;
- uaquit= 1;
-
- if(log != NULL)
- fclose(log);
- break;
- default:
- return;
- };
- if (!SetServiceStatus(hServiceStatusHandle, &ServiceStatus))
- {
- DWORD nError = GetLastError();
- }
- }
-
-
- void WINAPI service_main(int argc, char** argv)
- {
- ServiceStatus.dwServiceType = SERVICE_WIN32;
- ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
- ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_PAUSE_CONTINUE;
- ServiceStatus.dwWin32ExitCode = 0;
- ServiceStatus.dwServiceSpecificExitCode = 0;
- ServiceStatus.dwCheckPoint = 0;
- ServiceStatus.dwWaitHint = 0;
- hServiceStatusHandle = RegisterServiceCtrlHandler(_T(SERVICE_NAME), ServiceHandler);
- if (hServiceStatusHandle==0)
- {
- DWORD nError = GetLastError();
- }
-
- log = fopen("c:\\test.txt","w");
-
- HANDLE task_handle = CreateThread(NULL,NULL,srv_core_thread,NULL,NULL,NULL);
- if(task_handle == NULL)
- {
- fprintf(log,"create srv_core_thread failed\n");
- }
-
-
- ServiceStatus.dwCurrentState = SERVICE_RUNNING;
- ServiceStatus.dwCheckPoint = 0;
- ServiceStatus.dwWaitHint = 9000;
- if(!SetServiceStatus(hServiceStatusHandle, &ServiceStatus))
- {
- DWORD nError = GetLastError();
- }
-
- }
-
- int main (int argc, const char *argv[])
- {
- SERVICE_TABLE_ENTRY ServiceTable[2];
-
- ServiceTable[0].lpServiceName = _T(SERVICE_NAME);
- ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)service_main;
-
- ServiceTable[1].lpServiceName = NULL;
- ServiceTable[1].lpServiceProc = NULL;
-
- StartServiceCtrlDispatcher(ServiceTable);
- return 0;
- }
以上是一个别人写的简单服务,需要注意的是,win32控制台的应用程序,作为服务不能直接打开,因此也不能调试。
开启服务步骤如下:
1.编译程序;
2.成功后找到win32srvdemo.exe(注意:不是直接运行此程序),在debug或release目录中,
复制下路径,如..win32srvdemo\debug\win32srvdemo.exe;
3.开始->运行->cmd->回车 输入sc create test binPath= 上面的路径
4.开始->运行->services.msc->回车 找到test并启动->OK了
5.成功后应该可以看到c:\test.txt文件