This is an automated email from the ASF dual-hosted git repository.

jiuzhudong pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit a8280b0eee56d8c8a254373da73b6f6b24273500
Author: pengyinjie <[email protected]>
AuthorDate: Sat Oct 11 11:17:25 2025 +0800

    freopen: close old file descriptor before reopening
    
    Updated freopen function in libc stdio to close the old file descriptor 
before reopening the file.
    
    Signed-off-by: pengyinjie <[email protected]>
    Signed-off-by: ligd <[email protected]>
---
 libs/libc/stdio/lib_freopen.c | 23 +++++++++++++----------
 1 file changed, 13 insertions(+), 10 deletions(-)

diff --git a/libs/libc/stdio/lib_freopen.c b/libs/libc/stdio/lib_freopen.c
index 2297bfbdc06..9cc9f31b514 100644
--- a/libs/libc/stdio/lib_freopen.c
+++ b/libs/libc/stdio/lib_freopen.c
@@ -97,12 +97,6 @@ FAR FILE *freopen(FAR const char *path, FAR const char *mode,
           return NULL;
         }
 
-      fd = open(path, oflags, 0666);
-      if (fd < 0)
-        {
-          return NULL;
-        }
-
       /* Make sure that we have exclusive access to the stream */
 
       flockfile(stream);
@@ -117,11 +111,20 @@ FAR FILE *freopen(FAR const char *path, FAR const char 
*mode,
 
       funlockfile(stream);
 
-      /* Duplicate the new fd to the stream. */
+      /* close the old fd */
 
-      ret = dup2(fd, fileno(stream));
-      close(fd);
-      if (ret < 0)
+      close(fileno(stream));
+
+      /* Open the new file and reused the fd */
+
+      fd = open(path, oflags, 0666);
+      flockfile(stream);
+      stream->fs_cookie = (FAR void *)(intptr_t)fd;
+      funlockfile(stream);
+
+      /* To clear the stale fd */
+
+      if (fd < 0)
         {
           return NULL;
         }

Reply via email to