#include <Windows.h> #include <iostream> int main() { SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hSCM == NULL) { // 处理错误 return -1; } SC_HANDLE hService = OpenService(hSCM, L"EventLog", SERVICE_START); if (hService == NULL) { // 处理错误 CloseServiceHandle(hSCM); return -1; } if (!StartService(hService, 0, NULL)) { // 处理错误 CloseServiceHandle(hService); CloseServiceHandle(hSCM); return -1; } CloseServiceHandle(hService); CloseServiceHandle(hSCM); while(true) { DWORD pid = GetCurrentProcessId(); std::cout << "Current process ID: " << pid << std::endl; Sleep(2000); // 暂停 2 秒钟 } return 0; } 以上程序未进入死循环,执行一次就退出了。
时间: 2023-11-27 09:55:08 浏览: 96
这是因为在程序的最后,return 0;语句会导致程序正常退出。如果想让程序一直运行下去,可以将while循环放在return 0;语句前面,或者将return 0;删除即可。例如:
```
#include <Windows.h>
#include <iostream>
int main()
{
SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
{
// 处理错误
return -1;
}
SC_HANDLE hService = OpenService(hSCM, L"EventLog", SERVICE_START);
if (hService == NULL)
{
// 处理错误
CloseServiceHandle(hSCM);
return -1;
}
if (!StartService(hService, 0, NULL))
{
// 处理错误
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return -1;
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
while (true)
{
DWORD pid = GetCurrentProcessId();
std::cout << "Current process ID: " << pid << std::endl;
Sleep(2000); // 暂停 2 秒钟
}
}
```
阅读全文