C语言编写Windows服务程序
原文:C语言编写Windows服务程序

#include <Windows.h>
#include <stdio.h>#define SLEEP_TIME 5000                          // 间隔时间
#define LOGFILE "C:\\memstatus.txt"              // 信息输出文件SERVICE_STATUS ServiceStatus;  // 服务状态
SERVICE_STATUS_HANDLE hStatus; // 服务状态句柄void  ServiceMain(int argc, char** argv);
void  CtrlHandler(DWORD request);
int InitService();int WriteToLog(char* str)
{FILE* pfile;fopen_s(&pfile,LOGFILE,"a+");if (pfile==NULL){return -1;}fprintf_s(pfile,"%s\n",str);fclose(pfile);return 0;
}// Service initialization
int InitService()
{ OutputDebugString("Monitoring started.");int result;result = WriteToLog("Monitoring started.");return(result);
}
// Control Handler
void  CtrlHandler(DWORD request)
{switch (request){case SERVICE_CONTROL_STOP:OutputDebugString("Monitoring stopped.");WriteToLog("Monitoring stopped.");ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus (hStatus, &ServiceStatus);return;case SERVICE_CONTROL_SHUTDOWN:OutputDebugString("Monitoring stopped.");WriteToLog("Monitoring stopped.");ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus (hStatus, &ServiceStatus);return;default:break;}// Report current statusSetServiceStatus (hStatus, &ServiceStatus);return;
}void  ServiceMain(int argc, char** argv)
{int error;ServiceStatus.dwServiceType = SERVICE_WIN32;ServiceStatus.dwCurrentState = SERVICE_START_PENDING;ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP;//在本例中只接受系统关机和停止服务两种控制命令ServiceStatus.dwWin32ExitCode = 0;ServiceStatus.dwServiceSpecificExitCode = 0;ServiceStatus.dwCheckPoint = 0;ServiceStatus.dwWaitHint = 0;hStatus = ::RegisterServiceCtrlHandler("MemoryStatus", (LPHANDLER_FUNCTION)CtrlHandler);if (hStatus == (SERVICE_STATUS_HANDLE)0){WriteToLog("RegisterServiceCtrlHandler failed");return;}WriteToLog("RegisterServiceCtrlHandler success");// Initialize Service error = InitService();if (error) {// Initialization failedServiceStatus.dwCurrentState = SERVICE_STOPPED; ServiceStatus.dwWin32ExitCode = -1; SetServiceStatus(hStatus, &ServiceStatus); return; } // 向SCM 报告运行状态ServiceStatus.dwCurrentState = SERVICE_RUNNING;SetServiceStatus (hStatus, &ServiceStatus);// 下面就开始任务循环了,你可以添加你自己希望服务做的工作MEMORYSTATUS memstatus;while (ServiceStatus.dwCurrentState == SERVICE_RUNNING){char buffer[16];GlobalMemoryStatus(&memstatus);int availmb = memstatus.dwAvailPhys/1024/1024;sprintf_s(buffer,100,"available memory is %dMB",availmb);OutputDebugString(buffer);int result = WriteToLog(buffer);if (result){ServiceStatus.dwCurrentState = SERVICE_STOPPED; ServiceStatus.dwWin32ExitCode      = -1; SetServiceStatus(hStatus, &ServiceStatus);return;}Sleep(SLEEP_TIME);}WriteToLog("service stopped");
}void main()
{SERVICE_TABLE_ENTRY ServiceTable[2];ServiceTable[0].lpServiceName="MemoryStatus";ServiceTable[0].lpServiceProc=(LPSERVICE_MAIN_FUNCTION)ServiceMain;ServiceTable[1].lpServiceName=NULL;ServiceTable[1].lpServiceProc=NULL;StartServiceCtrlDispatcher(ServiceTable);}

命令行操作:

注意我这里在sc create MemortyStatus binpath= D:\MemoryStatus.exe里面有个拼写错误,MemoryStatus写成了MemortyStatus,多了个t,这个没关系,只要你在下面操作时候将错就错就行了。

运行结果:

最后,停止和删除服务:

参考:

http://www.vckbase.com/index.php/wv/1193

http://www.2cto.com/kf/201111/111990.html

posted on 2014-12-16 08:10 NET未来之路 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/4166269.html

C语言编写Windows服务程序相关推荐

  1. 用 C 语言编写 Windows 服务程序的五个步骤

    前一段时间我写了一篇通过写服务的形式来达到一些监视程序运行的目的的文章,至于如何在windows下写服务我没有详细介绍,今天就让我们一起看看如何来写服务程序. Windows 服务被设计用于需要在后台 ...

  2. C++语言编写windows服务

    C++语言编写windows服务 1 windows服务 2 DebugView调试工具 3 c语言编写windows服务 4 将程序作为windows服务 1. windows服务 通过快捷键&qu ...

  3. c语言编写系统服务程序,C语言Windows服务程序编写-ServiceMain

    C语言编写的Windows服务程序,可以类比Linux/Unix环境下的daemon进程. 一下是VS2010环境下的demo: // windows_service.cpp : 定义控制台应用程序的 ...

  4. 编写Windows服务程序,将Python作为Windows服务启动

    首先需要安装两个模块. pip install pywin32 -i https://pypi.tuna.tsinghua.edu.cn/simplepip install pyinstaller - ...

  5. C#编写Windows服务程序 (服务端),客户端使用 消息队列 实现淘宝 订单全链路效果

    需求: 针对 淘宝提出的 订单全链路 产品接入 .http://open.taobao.com/doc/detail.htm?id=102423&qq-pf-to=pcqq.group oms ...

  6. C#编写Windows服务程序 (服务端),client使用 消息队列 实现淘宝 订单全链路效果

    需求: 针对 淘宝提出的 订单全链路 产品接入 .http://open.taobao.com/doc/detail.htm?id=102423&qq-pf-to=pcqq.group oms ...

  7. C#编写Windows服务程序图文教程

    Windows Service这一块并不复杂,但是注意事项太多了,网上资料也很凌乱,偶尔自己写也会丢三落四的.所以本文也就产生了,本文不会写复杂的东西,完全以基础应用的需求来写,所以不会对Window ...

  8. C++编写Windows服务程序

    环境 VC6.0 代码 #include "windows.h" SERVICE_STATUS          gSvcStatus;  //服务状态 SERVICE_STATU ...

  9. python开发服务程序_Python 编写Windows服务程序:将Python作为Windows服务启动 | 学步园...

    Python程序作为Windows服务启动,需要安装pywin32包.下载路径: #-*- coding:utf-8 -*- import win32serviceutil import win32s ...

最新文章

  1. 女朋友什么的都是浮云,代码才是真爱!
  2. Vware Workstation pro 12|虚拟机
  3. C# 学习笔记(11)蓝屏小工具
  4. stm32之spi之NSS管脚信号
  5. linux下安装navicat并生成桌面图标
  6. @vue/cli启动异常:ENOENT: no such file or directory, scandir
  7. 顺序容器及其常用函数
  8. jdk卸载不干净怎么办_雨刮器“刮不干净”怎么办?老司机:用这招,分分钟解决!...
  9. 通过暴露出来的OA和github信息拿Shell
  10. linux 系统下如何进行用户之间的切换
  11. 使用for循环遍历文件、使用while循环遍历文件
  12. 前端开发:报错Error in created hook:”SyntaxError:Unexpected token u in JSON at position 0”…解决方法
  13. 工作中个人注册的媒体账号离职要归公司所有?
  14. bugku CTF杂项wp(1)
  15. 如何关闭服务器系统防火墙设置方法,怎么关闭防火墙 Windows自带防火墙关闭方法...
  16. 计算机导论——程序设计基础07
  17. Vue经典实例之table表格奇偶行不同颜色、鼠标移入变色、点击变色,一看就明白
  18. 浅析TVS管和ESD有什么区别?
  19. 【小程序】tabbar用法
  20. PCL voxelgrid实现

热门文章

  1. python自动化从零开始_从零开始的自动化测试框架——Python篇
  2. 添加白名单_上网行为管理如何添加网站白名单(包括https网站)
  3. All in one:如何搭建端到端可观测体系
  4. 函数计算 GB 镜像秒级启动:下一代软硬件架构协同优化
  5. 课程升级 | 极速构建知识体系,即学即用 Serverless
  6. 如何复制粘贴_年终工作总结如何写?复制粘贴肯定不行啦
  7. python动态排名可视化_动态排名可视化 | 带你领略编程语言20年风云变化
  8. .net 遍历数组找重复值写入一个新数组_面试 | 数组类算法精析
  9. Deep-Learning-YOLOV4实践:ScaledYOLOv4模型训练自己的数据集调试问题总结
  10. 【阿里云课程】神经网络:从生物学机制到全连接神经网络的局限性