about summary refs log tree commit diff
path: root/src/stdio/freopen.c
diff options
context:
space:
mode:
authorRich Felker <dalias@aerifal.cx>2012-10-24 21:16:06 -0400
committerRich Felker <dalias@aerifal.cx>2012-10-24 21:16:06 -0400
commit892cafff665b44d238e3b664f61ca38dd965cba6 (patch)
treec65353fe88b0d78025e113b77ed8728a2b4bc8d4 /src/stdio/freopen.c
parent708c91f4e9be2cfd6d35e71361956e13f3201b85 (diff)
downloadmusl-892cafff665b44d238e3b664f61ca38dd965cba6.tar.gz
musl-892cafff665b44d238e3b664f61ca38dd965cba6.tar.xz
musl-892cafff665b44d238e3b664f61ca38dd965cba6.zip
greatly improve freopen behavior
1. don't open /dev/null just as a basis to copy flags; use shared
__fmodeflags function to get the right file flags for the mode.

2. handle the case (probably invalid, but whatever) case where the
original stream's file descriptor was closed; previously, the logic
re-closed it.

3. accept the "e" mode flag for close-on-exec; update dup3 to fallback
to using dup2 so we can simply call __dup3 instead of putting fallback
logic in freopen itself.
Diffstat (limited to 'src/stdio/freopen.c')
-rw-r--r--src/stdio/freopen.c17
1 files changed, 10 insertions, 7 deletions
diff --git a/src/stdio/freopen.c b/src/stdio/freopen.c
index 5b4f126d..c80ce3b4 100644
--- a/src/stdio/freopen.c
+++ b/src/stdio/freopen.c
@@ -7,24 +7,27 @@
 /* Locking is not necessary because, in the event of failure, the stream
  * passed to freopen is invalid as soon as freopen is called. */
 
+int __dup3(int, int, int);
+
 FILE *freopen(const char *restrict filename, const char *restrict mode, FILE *restrict f)
 {
-	int fl;
+	int fl = __fmodeflags(mode);
 	FILE *f2;
 
 	fflush(f);
 
 	if (!filename) {
-		f2 = fopen("/dev/null", mode);
-		if (!f2) goto fail;
-		fl = __syscall(SYS_fcntl, f2->fd, F_GETFL, 0);
+		if (fl&O_CLOEXEC)
+			__syscall(SYS_fcntl, f->fd, F_SETFD, FD_CLOEXEC);
+		fl &= ~(O_CREAT|O_EXCL|O_CLOEXEC);
 		if (syscall(SYS_fcntl, f->fd, F_SETFL, fl) < 0)
-			goto fail2;
+			goto fail;
+		return f;
 	} else {
 		f2 = fopen(filename, mode);
 		if (!f2) goto fail;
-		if (syscall(SYS_dup2, f2->fd, f->fd) < 0)
-			goto fail2;
+		if (f2->fd == f->fd) f2->fd = -1; /* avoid closing in fclose */
+		else if (__dup3(f2->fd, f->fd, fl&O_CLOEXEC)<0) goto fail2;
 	}
 
 	f->flags = (f->flags & F_PERM) | f2->flags;