Skip to content

Commit

Permalink
win32: Close service log file on finished
Browse files Browse the repository at this point in the history
  • Loading branch information
kumajaya committed May 7, 2024
1 parent c12d573 commit 5364279
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/arch/win32/service/wmain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,23 @@ int _main(int argc, char *arg[]);


// Modified from https://stackoverflow.com/a/21376268
void EnableLogRedirection(const std::wstring &fname, std::FILE *fstream)
typedef std::vector<std::FILE*> TFileList;
void EnableLogRedirection(TFileList &lstream, const std::wstring &fname, std::FILE *fstream)
{
// Duplicate stdout/stderr and give it a new file descriptor
int fd = _dup((fstream == stdout) ? STDOUT_FILENO : STDERR_FILENO);
if (fd != -1)
{
// Re-open stdout/stderr to the new file
_wfreopen(fname.c_str(), (PWSTR)L"w", fstream);
std::FILE *stream = _wfreopen(fname.c_str(), (PWSTR)L"w", fstream);
if (stream != NULL)
{
fflush(fstream);
// Close the new file later
lstream.push_back(stream);
}
_close(fd);
}

fflush(fstream);
}


Expand Down Expand Up @@ -137,6 +142,7 @@ int wmain(int argc, wchar_t *argv[])
else if (_wcsicmp(L"service", argv[1] + 1) == 0 || _wcsicmp(L"s", argv[1] + 1) == 0)
{
// Start setup stdout/stderr redirection
TFileList logstream;
wchar_t szPath[MAX_PATH];
if (GetModuleFileNameW(NULL, szPath, ARRAYSIZE(szPath)) == 0) {
DEVLOG_ERROR("GetModuleFileNameW failed w/err 0x%08lx\n", GetLastError());
Expand All @@ -146,16 +152,26 @@ int wmain(int argc, wchar_t *argv[])
// Disable logging with "-service nolog" argument
if (std::filesystem::exists(fullpath) && _wcsicmp(L"nolog", argv[2]) != 0) {
std::wstring logfile = fullpath.replace_extension("log").wstring();
EnableLogRedirection(logfile, stdout);
EnableLogRedirection(logstream, logfile, stdout);
logfile = fullpath.replace_extension("err").wstring();
EnableLogRedirection(logfile, stderr);
EnableLogRedirection(logstream, logfile, stderr);
}

CForteService service(SERVICE_DISPLAY_NAME, static_cast<int>(l_argv.size() - 1), l_argv.data());
if (!CServiceBase::Run(service))
{
DEVLOG_ERROR("Service failed to run w/err 0x%08lx\n", GetLastError());
}

// Close the log file
for(auto &stream : logstream)
{
if (stream != NULL)
{
fclose(stream);
}
}
logstream.clear();
}
else
{
Expand Down

0 comments on commit 5364279

Please sign in to comment.