Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fs: use dup/dup2 for stdio hide and restore #597

Merged
merged 6 commits into from
Nov 20, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 22 additions & 11 deletions src/sys/fs.c
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,15 @@
#define open _open
#define read _read
#define close _close
#define dup _dup
#define dup2 _dup2
#define fileno _fileno
#endif


static int dup_stdout = -1;
static int dup_stderr = -1;

/**
* Create a directory with full path
*
Expand Down Expand Up @@ -211,25 +217,30 @@ int fs_fopen(FILE **fp, const char *file, const char *mode)


/**
* Hide/Close stdout and stderr output
* Hide/Close stdout and stderr output (no THREAD-SAFETY)
*/
void fs_stdio_hide(void)
{
(void)fclose(stdout);
(void)fclose(stderr);
dup_stdout = dup(fileno(stdout));
dup_stderr = dup(fileno(stderr));
#ifdef WIN32
int fd = open("nul", O_WRONLY);
#else
int fd = open("/dev/null", O_WRONLY);
#endif
(void)dup2(fd, fileno(stdout));
(void)dup2(fd, fileno(stderr));
}


/**
* Restore stdout and stderr output
* Restore stdout and stderr output (no THREAD-SAFETY)
*/
void fs_stdio_restore(void)
{
#ifdef WIN32
(void)freopen("CON", "w", stdout);
(void)freopen("CON", "w", stderr);
#else
(void)freopen("/dev/tty", "w", stdout);
(void)freopen("/dev/tty", "w", stderr);
#endif
if (dup_stdout < 0 || dup_stderr < 0)
return;

(void)dup2(dup_stdout, fileno(stdout));
(void)dup2(dup_stderr, fileno(stderr));
}