Files
cxxLibrary/test/serviceTest.cpp

91 lines
2.3 KiB
C++
Raw Normal View History

2026-03-29 19:02:44 +08:00
#include <iostream>
#include <string>
#include <tchar.h>
#include <thread>
#include <zoost/zoost.h>
class TestFunction
{
public:
TestFunction() = default;
public:
void Start()
{
isRun_ = true;
task_ = std::thread([this]() { monitor(); });
}
void Exec()
{
}
void monitor()
{
int counter = 0;
while (isRun_) {
std::this_thread::sleep_for(std::chrono::seconds(3));
FILE* logFile = fopen("D:\\MyServiceLog.txt", "a");
if (logFile) {
fprintf(logFile, "CppService running - Counter: %d\n", counter++);
fclose(logFile);
}
}
}
void Stop()
{
std::this_thread::sleep_for(std::chrono::seconds(2));
isRun_ = false;
if (task_.joinable()) {
task_.join();
}
}
public:
bool isRun_{false};
std::thread task_{};
};
int main(int argc, char* argv[])
{
zoostCommon::SetOutputU8();
zoostWinService::serviceName_ = "TaynpgTest";
zoostWinService::dispName_ = "My C++ Windows Service";
TestFunction tf;
zoostWinService::exeFunc_ = [&tf]() { tf.Exec(); };
zoostWinService::stopFunc_ = [&tf]() { tf.Stop(); };
if (argc > 1) {
std::string command = argv[1];
if (command == "install") {
auto r = zoostWinService::WinInstallService();
if (!r) {
std::cout << zoostWinService::GetLastErrorMsg() << std::endl;
}
return r;
} else if (command == "uninstall") {
return zoostWinService::WinUninstallService();
} else if (command == "run") {
// 这里直接执行,用于调试。
return 0;
} else {
std::cout << zoostWinService::serviceName_ << "服务程序。\n";
std::cout << argv[0];
std::cout << " 参数用法:\n"
<< " install 安装服务\n"
<< " uninstall 卸载服务\n"
<< " run 控制台模式运行\n"
<< " 直接运行 作为服务启动\n";
return 1;
}
}
// 这里执行
tf.Start();
zoostWinService::WinServiceRun();
return 0;
}