Chinaunix首页 | 论坛 | 博客
  • 博客访问: 326858
  • 博文数量: 64
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 589
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-08 15:50
文章分类

全部博文(64)

文章存档

2015年(52)

2014年(3)

2013年(9)

我的朋友

分类: WINDOWS

2015-07-25 14:41:29

#include <windows.h>
#include <winsvc.h>
#include <stdio.h>


void control_service()
{
 // 打开服务管理对象
 SC_HANDLE hSC = OpenSCManager( NULL, 
 NULL, GENERIC_EXECUTE);
 if( hSC == NULL)
 {
printf("OpenScManager error:%d\n",GetLastError());
 return;
 }
 // 打开打印服务。
 SC_HANDLE hSvc = OpenService( hSC, "Spooler",
 SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_STOP);
 if( hSvc == NULL)
 {
printf("OpenService error:%d\n",GetLastError());
CloseServiceHandle( hSC);
return;
 }
 // 获得服务的状态
 SERVICE_STATUS status;
 if( QueryServiceStatus( hSvc, &status) == FALSE)
 {
printf("QueryServiceStatus error:%d\n",GetLastError());
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
 }
 //如果处于停止状态则启动服务,否则停止服务。
 if( status.dwCurrentState == SERVICE_RUNNING)
 {
// 停止服务
if( ControlService( hSvc, 
SERVICE_CONTROL_STOP, &status) == FALSE)
{
printf("ControlService Stop error:%d\n",GetLastError());
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
}
// 等待服务停止
while( QueryServiceStatus( hSvc, &status) == TRUE)
{
Sleep( status.dwWaitHint);
if( status.dwCurrentState == SERVICE_STOPPED)
{
printf("QueryServiceStatus stop success.\n");
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
}
}
 }else if( status.dwCurrentState == SERVICE_STOPPED){
// 启动服务
if( StartService( hSvc, NULL, NULL) == FALSE)
{
printf("start service error:%d\n",GetLastError());
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
}
// 等待服务启动
while( QueryServiceStatus( hSvc, &status) == TRUE)
{
Sleep( status.dwWaitHint);
if( status.dwCurrentState == SERVICE_RUNNING)
{
printf("start success.\n");
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
}
}
 }
printf("Start error:%d\n",GetLastError());
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
}


int main()
{
control_service();
while(1){
Sleep(1000);
}
return 0;
}
阅读(4081) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~