#include
#include
#include
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;
}
阅读(3948) | 评论(0) | 转发(0) |