Skip to content

Commit

Permalink
win32: Update stdout/stderr redirection
Browse files Browse the repository at this point in the history
  • Loading branch information
kumajaya committed May 4, 2024
1 parent 2fcd345 commit a960c83
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions src/arch/win32/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -181,33 +181,43 @@ static int convertArguments(int argc, wchar_t *argw[], std::vector<std::string>
}

// Modified from https://stackoverflow.com/a/21376268
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
static std::vector<int> s_fdesc;
static void startRedirection(const char *fname, FILE *fstream, std::vector<int> &fdesc) {
// Duplicate stdout/stderr and give it a new file descriptor
int i = _dup(_fileno(fstream));
int i = _dup(fstream == stdout ? STDOUT_FILENO : STDERR_FILENO);
fdesc.push_back(i);

// Re-open stdout/stderr to the new file
freopen(fname, "w", fstream);

DEVLOG_INFO("Redirection std%s to file started\n", fstream == stdout ? "out" : "err");
if (i != -1) {
// Re-open stdout/stderr to the new file
if (std::freopen(fname, "w", fstream)) {
DEVLOG_INFO("Redirect std%s[%d] to %s started\n",
fstream == stdout ? "out" : "err", i, fname);
}
}
}

static bool stopRedirection(FILE *fstream, std::vector<int> &fdesc) {
bool ret = false;
if (fdesc.size() != 0) {
// Get last saved file descriptor and restore it
int i = fdesc.back();
_dup2(i, _fileno(fstream));

// Need to close the file associated with the saved file descriptor
_close(i);
if (i != -1) {
_dup2(i, fstream == stdout ? STDOUT_FILENO : STDERR_FILENO);
// Need to close the file associated with the saved file descriptor
if (_close(i) == 0) {
ret = true;
DEVLOG_INFO("Redirect std%s[%d] to file stopped\n",
fstream == stdout ? "out" : "err", i);
}
}

fdesc.pop_back();
DEVLOG_INFO("Redirection std%s to file stopped\n", fstream == stdout ? "out" : "err");
return true;
}

return false;
return ret;
}

//
Expand Down

0 comments on commit a960c83

Please sign in to comment.