#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; } while (true) { DWORD pid = GetCurrentProcessId(); std::cout << "Current process ID: " << pid << std::endl; Sleep(2000); // 暂停 2 秒钟 } CloseServiceHandle(hService); CloseServiceHandle(hSCM); return 0; } 以上代码如何让返回值为-1也不退出
时间: 2023-11-28 16:04:50 浏览: 37
可以在while循环外添加一个标志变量,当需要让程序不退出时,将标志变量设置为true,否则设置为false。while循环条件改为判断该标志变量的值,如果为true则继续循环,否则跳出循环并结束程序。示例代码如下:
```c++
#include <Windows.h>
#include <iostream>
bool continueRunning = true; // 定义标志变量
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;
}
while (continueRunning) { // 循环条件改为判断标志变量
DWORD pid = GetCurrentProcessId();
std::cout << "Current process ID: " << pid << std::endl;
Sleep(2000); // 暂停 2 秒钟
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return 0;
}
```
这样,当需要让程序不退出时,只需要将标志变量设置为true即可。当需要退出程序时,将标志变量设置为false即可。
阅读全文