Skip to contentSkip to conversation

cmdline: use freopen() to reopen standard streams

PATCH New Simon Rowe 1 participant 2 messages Mar 24, 2023

lore
Share & tools
lore

Simon Rowe

author
#0 lore raw

PATCH 1/2 cmdline: use freopen() to reopen standard streams

In glibc stdin, stdout & stderr are variables that can be assigned to
(https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html)
however this not necessarily true of other C libraries.

The gentoo musl porting notes
(https://wiki.gentoo.org/wiki/Musl_porting_notes)
recommend the substitution of

    stdX = fopen(...)

with

    freopen(..., stdX)
---
 tools/lvmcmdline.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
tools/lvmcmdline.c +12 -0
index a5bb6a5c5..dafff5ba4 100644
@@ -3422,7 +3422,11 @@ static int _check_standard_fds(void)
 	int err = is_valid_fd(STDERR_FILENO);
 
 	if (!is_valid_fd(STDIN_FILENO) &&
+#ifdef __GLIBC__
 	    !(stdin = fopen(_PATH_DEVNULL, "r"))) {
+#else
+	    !freopen(_PATH_DEVNULL, "r", stdin)) {
+#endif
 		if (err)
 			perror("stdin stream open");
 		else
@@ -3432,7 +3436,11 @@ static int _check_standard_fds(void)
 	}
 
 	if (!is_valid_fd(STDOUT_FILENO) &&
+#ifdef __GLIBC__
 	    !(stdout = fopen(_PATH_DEVNULL, "w"))) {
+#else
+	    !freopen(_PATH_DEVNULL, "w", stdout)) {
+#endif
 		if (err)
 			perror("stdout stream open");
 		/* else no stdout */
@@ -3440,7 +3448,11 @@ static int _check_standard_fds(void)
 	}
 
 	if (!is_valid_fd(STDERR_FILENO) &&
+#ifdef __GLIBC__
 	    !(stderr = fopen(_PATH_DEVNULL, "w"))) {
+#else
+	    !freopen(_PATH_DEVNULL, "w", stderr)) {
+#endif
 		printf("stderr stream open: %s\n",
 		       strerror(errno));
 		return 0;
Signature · 1 line
2.22.3
author
#1 lore raw

PATCH 2/2 log: use freopen() to reopen standard streams

In glibc stdin, stdout & stderr are variables that can be assigned to
(https://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html)
however this not necessarily true of other C libraries.

The gentoo musl porting notes
(https://wiki.gentoo.org/wiki/Musl_porting_notes)
recommend the substitution of

    stdX = fopen(...)

with

    freopen(..., stdX)
---
 lib/log/log.c | 4 ++++
 1 file changed, 4 insertions(+)
lib/log/log.c +4 -0
index 118a3ba42..a94016d81 100644
@@ -208,7 +208,11 @@ int reopen_standard_stream(FILE **stream, const char *mode)
 
 	_check_and_replace_standard_log_streams(old_stream, new_stream);
 
+#ifdef __GLIBC__
 	*stream = new_stream;
+#else
+	freopen(NULL, mode, *stream);
+#endif
 	return 1;
 }
 
Signature · 1 line
2.22.3