about summary refs log tree commit diff
path: root/libio/freopen.c
diff options
context:
space:
mode:
Diffstat (limited to 'libio/freopen.c')
-rw-r--r--libio/freopen.c29
1 files changed, 16 insertions, 13 deletions
diff --git a/libio/freopen.c b/libio/freopen.c
index abf19e96f1..6ce74ae449 100644
--- a/libio/freopen.c
+++ b/libio/freopen.c
@@ -24,28 +24,34 @@
    This exception applies to code released by its copyright holders
    in files containing the exception.  */
 
-#include "libioP.h"
-#include "stdio.h"
+#include <stdio.h>
 #include <fcntl.h>
 #include <stdlib.h>
 #include <unistd.h>
 
-#include <shlib-compat.h>
+#include <libioP.h>
 #include <fd_to_filename.h>
-
-#include <kernel-features.h>
+#include <shlib-compat.h>
 
 FILE *
 freopen (const char *filename, const char *mode, FILE *fp)
 {
-  FILE *result;
+  FILE *result = NULL;
+  char fdfilename[FD_TO_FILENAME_SIZE];
+
   CHECK_FILE (fp, NULL);
-  if (!(fp->_flags & _IO_IS_FILEBUF))
-    return NULL;
+
   _IO_acquire_lock (fp);
+  /* First flush the stream (failure should be ignored).  */
+  _IO_SYNC (fp);
+
+  if (!(fp->_flags & _IO_IS_FILEBUF))
+    goto end;
+
   int fd = _IO_fileno (fp);
-  const char *gfilename = (filename == NULL && fd >= 0
-			   ? fd_to_filename (fd) : filename);
+  const char *gfilename
+    = filename != NULL ? filename : fd_to_filename (fd, fdfilename);
+
   fp->_flags2 |= _IO_FLAGS2_NOCLOSE;
 #if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_1)
   if (&_IO_stdin_used == NULL)
@@ -101,9 +107,6 @@ freopen (const char *filename, const char *mode, FILE *fp)
     __close (fd);
 
 end:
-  if (filename == NULL)
-    free ((char *) gfilename);
-
   _IO_release_lock (fp);
   return result;
 }