#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include <aclapi.h> #pragma comment(lib, "advapi32.lib") TCHAR szCommand[];
TCHAR szSvcName[]; SC_HANDLE schSCManager;
SC_HANDLE schService; VOID __stdcall DisplayUsage(void); VOID __stdcall DoStartSvc(void);
VOID __stdcall DoUpdateSvcDacl(void);
VOID __stdcall DoStopSvc(void); BOOL __stdcall StopDependentServices(void); //
// Purpose:
// Entry point function. Executes specified command from user.
//
// Parameters:
// Command-line syntax is: svccontrol [command] [service_name]
//
// Return value:
// None
//
void _tmain(int argc, TCHAR *argv[])
{
printf("\n");
if( argc != )
{
printf("ERROR: Incorrect number of arguments\n\n");
DisplayUsage();
return;
} StringCchCopy(szCommand, , argv[]);
StringCchCopy(szSvcName, , argv[]); if (lstrcmpi( szCommand, TEXT("start")) == )
DoStartSvc();
else if (lstrcmpi( szCommand, TEXT("dacl")) == )
DoUpdateSvcDacl();
else if (lstrcmpi( szCommand, TEXT("stop")) == )
DoStopSvc();
else
{
_tprintf(TEXT("Unknown command (%s)\n\n"), szCommand);
DisplayUsage();
}
} VOID __stdcall DisplayUsage()
{
printf("Description:\n");
printf("\tCommand-line tool that controls a service.\n\n");
printf("Usage:\n");
printf("\tsvccontrol [command] [service_name]\n\n");
printf("\t[command]\n");
printf("\t start\n");
printf("\t dacl\n");
printf("\t stop\n");
} //
// Purpose:
// Starts the service if possible.
//
// Parameters:
// None
//
// Return value:
// None
//
VOID __stdcall DoStartSvc()
{
SERVICE_STATUS_PROCESS ssStatus;
DWORD dwOldCheckPoint;
DWORD dwStartTickCount;
DWORD dwWaitTime;
DWORD dwBytesNeeded; // Get a handle to the SCM database. schSCManager = OpenSCManager(
NULL, // local computer
NULL, // servicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights if (NULL == schSCManager)
{
printf("OpenSCManager failed (%d)\n", GetLastError());
return;
} // Get a handle to the service. schService = OpenService(
schSCManager, // SCM database
szSvcName, // name of service
SERVICE_ALL_ACCESS); // full access if (schService == NULL)
{
printf("OpenService failed (%d)\n", GetLastError());
CloseServiceHandle(schSCManager);
return;
} // Check the status in case the service is not stopped. if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // information level
(LPBYTE) &ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // size needed if buffer is too small
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
} // Check if the service is already running. It would be possible
// to stop the service here, but for simplicity this example just returns. if(ssStatus.dwCurrentState != SERVICE_STOPPED && ssStatus.dwCurrentState != SERVICE_STOP_PENDING)
{
printf("Cannot start the service because it is already running\n");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
} // Save the tick count and initial checkpoint. dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint; // Wait for the service to stop before attempting to start it. while (ssStatus.dwCurrentState == SERVICE_STOP_PENDING)
{
// Do not wait longer than the wait hint. A good interval is
// one-tenth of the wait hint but not less than 1 second
// and not more than 10 seconds. dwWaitTime = ssStatus.dwWaitHint / ; if( dwWaitTime < )
dwWaitTime = ;
else if ( dwWaitTime > )
dwWaitTime = ; Sleep( dwWaitTime ); // Check the status until the service is no longer stop pending. if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // information level
(LPBYTE) &ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // size needed if buffer is too small
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
} if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
{
// Continue to wait and check. dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
}
else
{
if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
{
printf("Timeout waiting for service to stop\n");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}
}
} // Attempt to start the service. if (!StartService(
schService, // handle to service
, // number of arguments
NULL) ) // no arguments
{
printf("StartService failed (%d)\n", GetLastError());
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}
else printf("Service start pending...\n"); // Check the status until the service is no longer start pending. if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // info level
(LPBYTE) &ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // if buffer too small
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
} // Save the tick count and initial checkpoint. dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint; while (ssStatus.dwCurrentState == SERVICE_START_PENDING)
{
// Do not wait longer than the wait hint. A good interval is
// one-tenth the wait hint, but no less than 1 second and no
// more than 10 seconds. dwWaitTime = ssStatus.dwWaitHint / ; if( dwWaitTime < )
dwWaitTime = ;
else if ( dwWaitTime > )
dwWaitTime = ; Sleep( dwWaitTime ); // Check the status again. if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // info level
(LPBYTE) &ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // if buffer too small
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
break;
} if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
{
// Continue to wait and check. dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
}
else
{
if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
{
// No progress made within the wait hint.
break;
}
}
} // Determine whether the service is running. if (ssStatus.dwCurrentState == SERVICE_RUNNING)
{
printf("Service started successfully.\n");
}
else
{
printf("Service not started. \n");
printf(" Current State: %d\n", ssStatus.dwCurrentState);
printf(" Exit Code: %d\n", ssStatus.dwWin32ExitCode);
printf(" Check Point: %d\n", ssStatus.dwCheckPoint);
printf(" Wait Hint: %d\n", ssStatus.dwWaitHint);
} CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
} //
// Purpose:
// Updates the service DACL to grant start, stop, delete, and read
// control access to the Guest account.
//
// Parameters:
// None
//
// Return value:
// None
//
VOID __stdcall DoUpdateSvcDacl()
{
EXPLICIT_ACCESS ea;
SECURITY_DESCRIPTOR sd;
PSECURITY_DESCRIPTOR psd = NULL;
PACL pacl = NULL;
PACL pNewAcl = NULL;
BOOL bDaclPresent = FALSE;
BOOL bDaclDefaulted = FALSE;
DWORD dwError = ;
DWORD dwSize = ;
DWORD dwBytesNeeded = ; // Get a handle to the SCM database. schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights if (NULL == schSCManager)
{
printf("OpenSCManager failed (%d)\n", GetLastError());
return;
} // Get a handle to the service schService = OpenService(
schSCManager, // SCManager database
szSvcName, // name of service
READ_CONTROL | WRITE_DAC); // access if (schService == NULL)
{
printf("OpenService failed (%d)\n", GetLastError());
CloseServiceHandle(schSCManager);
return;
} // Get the current security descriptor. if (!QueryServiceObjectSecurity(schService,
DACL_SECURITY_INFORMATION,
&psd, // using NULL does not work on all versions
,
&dwBytesNeeded))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
dwSize = dwBytesNeeded;
psd = (PSECURITY_DESCRIPTOR)HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwSize);
if (psd == NULL)
{
// Note: HeapAlloc does not support GetLastError.
printf("HeapAlloc failed\n");
goto dacl_cleanup;
} if (!QueryServiceObjectSecurity(schService,
DACL_SECURITY_INFORMATION, psd, dwSize, &dwBytesNeeded))
{
printf("QueryServiceObjectSecurity failed (%d)\n", GetLastError());
goto dacl_cleanup;
}
}
else
{
printf("QueryServiceObjectSecurity failed (%d)\n", GetLastError());
goto dacl_cleanup;
}
} // Get the DACL. if (!GetSecurityDescriptorDacl(psd, &bDaclPresent, &pacl,
&bDaclDefaulted))
{
printf("GetSecurityDescriptorDacl failed(%d)\n", GetLastError());
goto dacl_cleanup;
} // Build the ACE. BuildExplicitAccessWithName(&ea, TEXT("GUEST"),
SERVICE_START | SERVICE_STOP | READ_CONTROL | DELETE,
SET_ACCESS, NO_INHERITANCE); dwError = SetEntriesInAcl(, &ea, pacl, &pNewAcl);
if (dwError != ERROR_SUCCESS)
{
printf("SetEntriesInAcl failed(%d)\n", dwError);
goto dacl_cleanup;
} // Initialize a new security descriptor. if (!InitializeSecurityDescriptor(&sd,
SECURITY_DESCRIPTOR_REVISION))
{
printf("InitializeSecurityDescriptor failed(%d)\n", GetLastError());
goto dacl_cleanup;
} // Set the new DACL in the security descriptor. if (!SetSecurityDescriptorDacl(&sd, TRUE, pNewAcl, FALSE))
{
printf("SetSecurityDescriptorDacl failed(%d)\n", GetLastError());
goto dacl_cleanup;
} // Set the new DACL for the service object. if (!SetServiceObjectSecurity(schService,
DACL_SECURITY_INFORMATION, &sd))
{
printf("SetServiceObjectSecurity failed(%d)\n", GetLastError());
goto dacl_cleanup;
}
else printf("Service DACL updated successfully\n"); dacl_cleanup:
CloseServiceHandle(schSCManager);
CloseServiceHandle(schService); if(NULL != pNewAcl)
LocalFree((HLOCAL)pNewAcl);
if(NULL != psd)
HeapFree(GetProcessHeap(), , (LPVOID)psd);
} //
// Purpose:
// Stops the service.
//
// Parameters:
// None
//
// Return value:
// None
//
VOID __stdcall DoStopSvc()
{
SERVICE_STATUS_PROCESS ssp;
DWORD dwStartTime = GetTickCount();
DWORD dwBytesNeeded;
DWORD dwTimeout = ; // 30-second time-out
DWORD dwWaitTime; // Get a handle to the SCM database. schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights if (NULL == schSCManager)
{
printf("OpenSCManager failed (%d)\n", GetLastError());
return;
} // Get a handle to the service. schService = OpenService(
schSCManager, // SCM database
szSvcName, // name of service
SERVICE_STOP |
SERVICE_QUERY_STATUS |
SERVICE_ENUMERATE_DEPENDENTS); if (schService == NULL)
{
printf("OpenService failed (%d)\n", GetLastError());
CloseServiceHandle(schSCManager);
return;
} // Make sure the service is not already stopped. if ( !QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
goto stop_cleanup;
} if ( ssp.dwCurrentState == SERVICE_STOPPED )
{
printf("Service is already stopped.\n");
goto stop_cleanup;
} // If a stop is pending, wait for it. while ( ssp.dwCurrentState == SERVICE_STOP_PENDING )
{
printf("Service stop pending...\n"); // Do not wait longer than the wait hint. A good interval is
// one-tenth of the wait hint but not less than 1 second
// and not more than 10 seconds. dwWaitTime = ssp.dwWaitHint / ; if( dwWaitTime < )
dwWaitTime = ;
else if ( dwWaitTime > )
dwWaitTime = ; Sleep( dwWaitTime ); if ( !QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
goto stop_cleanup;
} if ( ssp.dwCurrentState == SERVICE_STOPPED )
{
printf("Service stopped successfully.\n");
goto stop_cleanup;
} if ( GetTickCount() - dwStartTime > dwTimeout )
{
printf("Service stop timed out.\n");
goto stop_cleanup;
}
} // If the service is running, dependencies must be stopped first. StopDependentServices(); // Send a stop code to the service. if ( !ControlService(
schService,
SERVICE_CONTROL_STOP,
(LPSERVICE_STATUS) &ssp ) )
{
printf( "ControlService failed (%d)\n", GetLastError() );
goto stop_cleanup;
} // Wait for the service to stop. while ( ssp.dwCurrentState != SERVICE_STOPPED )
{
Sleep( ssp.dwWaitHint );
if ( !QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
printf( "QueryServiceStatusEx failed (%d)\n", GetLastError() );
goto stop_cleanup;
} if ( ssp.dwCurrentState == SERVICE_STOPPED )
break; if ( GetTickCount() - dwStartTime > dwTimeout )
{
printf( "Wait timed out\n" );
goto stop_cleanup;
}
}
printf("Service stopped successfully\n"); stop_cleanup:
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
} BOOL __stdcall StopDependentServices()
{
DWORD i;
DWORD dwBytesNeeded;
DWORD dwCount; LPENUM_SERVICE_STATUS lpDependencies = NULL;
ENUM_SERVICE_STATUS ess;
SC_HANDLE hDepService;
SERVICE_STATUS_PROCESS ssp; DWORD dwStartTime = GetTickCount();
DWORD dwTimeout = ; // 30-second time-out // Pass a zero-length buffer to get the required buffer size.
if ( EnumDependentServices( schService, SERVICE_ACTIVE,
lpDependencies, , &dwBytesNeeded, &dwCount ) )
{
// If the Enum call succeeds, then there are no dependent
// services, so do nothing.
return TRUE;
}
else
{
if ( GetLastError() != ERROR_MORE_DATA )
return FALSE; // Unexpected error // Allocate a buffer for the dependencies.
lpDependencies = (LPENUM_SERVICE_STATUS) HeapAlloc(
GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesNeeded ); if ( !lpDependencies )
return FALSE; __try {
// Enumerate the dependencies.
if ( !EnumDependentServices( schService, SERVICE_ACTIVE,
lpDependencies, dwBytesNeeded, &dwBytesNeeded,
&dwCount ) )
return FALSE; for ( i = ; i < dwCount; i++ )
{
ess = *(lpDependencies + i);
// Open the service.
hDepService = OpenService( schSCManager,
ess.lpServiceName,
SERVICE_STOP | SERVICE_QUERY_STATUS ); if ( !hDepService )
return FALSE; __try {
// Send a stop code.
if ( !ControlService( hDepService,
SERVICE_CONTROL_STOP,
(LPSERVICE_STATUS) &ssp ) )
return FALSE; // Wait for the service to stop.
while ( ssp.dwCurrentState != SERVICE_STOPPED )
{
Sleep( ssp.dwWaitHint );
if ( !QueryServiceStatusEx(
hDepService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
return FALSE; if ( ssp.dwCurrentState == SERVICE_STOPPED )
break; if ( GetTickCount() - dwStartTime > dwTimeout )
return FALSE;
}
}
__finally
{
// Always release the service handle.
CloseServiceHandle( hDepService );
}
}
}
__finally
{
// Always free the enumeration buffer.
HeapFree( GetProcessHeap(), , lpDependencies );
}
}
return TRUE;
}

这是MSDN上的例子,以管理员身份运行控制台。

windows服务控制(开启/停止已有服务)的更多相关文章

  1. linux/windows下启用和停止VMware后台服务的脚本

    linux/windows下启用和停止VMware后台服务的脚本 linux/windows下启用和停止VMware后台服务的脚本 linux平台 windows平台 本文由乌合之众 lym瞎编,欢迎 ...

  2. 开启Windows文件共享必须开启的两个服务

    开启Windows文件共享必须开启的两个服务分别是: 1.Server服务. 2.Workstation服务. 如果文件共享丢失,可以去首先去查看这两个服务是否停止,如果停止,请启动或者重启.

  3. MySQL 安装和启动服务,“本地计算机 上的 MySQL 服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止。”

    MySQL 安装和启动服务,以及遇到的问题 MySQL版本: mysql-5.7.13-winx64.zip (免安装,解压放到程序文件夹即可,比如 C:\Program Files\mysql-5. ...

  4. 本地计算机上的OracleOraDb11g_home1TNSListener服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止。——Oracle监听器服务无法启动!

    问题: oracle服务设置为手动启动.但是开机后手动启动监听服务后弹出框,提示“本地计算机上的OracleOraDb11g_home1TNSListener服务启动后停止.某些服务在未由其他服务或程 ...

  5. 本地计算机上的XXX服务启动后停止。某些服务在未由其它服务或程序使用时将自动停止。咋整?

    用C#写个windows服务,安装部署后去启动时,提示说“本地计算机上的XXX服务启动后停止.某些服务在未由其它服务或程序使用时将自动停止”.咋整?就像下面酱紫: 度娘说不知道咋整,我想把程序附加到w ...

  6. 本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动

    重新安装MySQL数据库,由于安装的时候马虎,一路next(事实上,某些地方需要严格的配置,我忘记注意了),导致现在出了很多麻烦. 错误信息: 本地计算机上的MySQL服务启动后停止.某些服务在未由其 ...

  7. 本机mysql 5.7服务启动后停止,某些服务在未有其他应用程序使用时停止

    本机mysql 5.7服务启动后停止,某些服务在未有其他应用程序使用时停止 出现这种报错,mysql服务启动不了: 错误的尝试: 1:尝试了这个博客:https://blog.csdn.net/wai ...

  8. mysql57重新安装后无法再次启动mysql57服务“本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动。”--解决方法

    本地计算机上的MySQL服务启动后停止.某些服务在未由其他服务或程序使用时将自动. (win10,mysql5.7+) 解决方法: 第一步:查看MySQL57安装路径 只要在programData路径 ...

  9. 本地计算机上的Apple Mobile Device服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止

    解决办法:1.开始--运行--regedit.exe,打开注册表编辑器,删除以下两个键: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Wi ...

随机推荐

  1. 虚拟机开启Linux时出现“我以复制虚拟机”、“我已移动虚拟机”

    当出现标题的情况时,并且网络出现状况时,可以尝试一下解决办法 首先用ifconfig -a命令调出现在的网卡驱动的名称和HWaddr地址,然后再编辑/etc/sysconfig/networking/ ...

  2. IOS 被拒 关于 iPhone running iOS 10.3.1 on Wi-Fi connected to an IPv6 network.

    问题: Guideline 2.1 - Performance Thank you for your resubmission. However, we discovered one or more ...

  3. Codeforces Round #390 (Div. 2) A B C D

    这是一场比较难的div2 ... 比赛的时候只出了AB A很有意思 给出n个数 要求随意的把相邻的数合并成任意多数 最后没有为0的数 输出合并区间个数与区间 可以想到0可以合到任何数上并不改变该数的性 ...

  4. sshfs的挂载与卸载

    在CentOS中 sshfs的使用依赖EPEL(只安装sshfs不会出错,但是却无法使用) 挂载 安装EPEL rpm -i https://dl.fedoraproject.org/pub/epel ...

  5. httpClient的post方法使用form格式数据调用接口

    Http使用post调用接口,接口只接受form表单数据格式问题? 这个问题的关键是form表单提交的是数据格式是什么样子的,使用httpClient工具类时Header信息如何写. 会影响解决问题思 ...

  6. VS10_慢_优化

    参考网址: http://blog.csdn.net/cll131421/article/details/15341367 1. 我暂时只做了这个: “ 一.VS2010选项视觉体验设置 工具-> ...

  7. C#下利用正则表达式实现字符串搜索功能的方法(转)

    关键字:正则表达式.元字符.字符串.匹配: 1.正则表达式简介:正则表达式提供了功能强大.灵活而又高效的方法来处:.NET框架正则表达式并入了其他正则表达式实现的: 2.字符串搜索:正则表达式语言由两 ...

  8. vue-router使用next()跳转到指定路径时会无限循环

    我在路由为 /path 的页面这样写 beforeRouteLeave (to, from, next) { console.log('离开路路由') if(to.fullPath==='/home' ...

  9. js对象数组 根据某个共同字段 分组

    var arr = [ {"id":"1001","name":"值1","value":" ...

  10. 水滴效果的下拉刷新--第三方开源 开源--WaveSwipeRefreshLayout

    下载地址:https://github.com/recruit-lifestyle/WaveSwipeRefreshLayout 直接把代码复制到你的项目于即可使用: 使用: 在xml中: <j ...