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 d49b83f
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/arch/win32/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -181,23 +181,26 @@ 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 (std::freopen(fname, "w", fstream)) {
DEVLOG_INFO("Redirection std%s to file started\n", fstream == stdout ? "out" : "err");
}
}

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

// Need to close the file associated with the saved file descriptor
_close(i);
Expand Down

0 comments on commit d49b83f

Please sign in to comment.