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 <pengyinjie@xiaomi.com>
Signed-off-by: ligd <liguiding1@xiaomi.com>
This commit is contained in:
pengyinjie
2025-10-11 11:17:25 +08:00
committed by Donny(董九柱)
parent acb9a1a296
commit a8280b0eee
+13 -10
View File
@@ -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;
}