1 #include "stdio_impl.h"
4 /* The basic idea of this implementation is to open a new FILE,
5 * hack the necessary parts of the new FILE into the old one, then
6 * close the new FILE. */
8 /* Locking IS necessary because another thread may provably hold the
9 * lock, via flockfile or otherwise, when freopen is called, and in that
10 * case, freopen cannot act until the lock is released. */
12 int __dup3(int, int, int);
14 FILE *freopen(const char *restrict filename, const char *restrict mode, FILE *restrict f)
16 int fl = __fmodeflags(mode);
25 __syscall(SYS_fcntl, f->fd, F_SETFD, FD_CLOEXEC);
26 fl &= ~(O_CREAT|O_EXCL|O_CLOEXEC);
27 if (syscall(SYS_fcntl, f->fd, F_SETFL, fl) < 0)
30 f2 = fopen(filename, mode);
32 if (f2->fd == f->fd) f2->fd = -1; /* avoid closing in fclose */
33 else if (__dup3(f2->fd, f->fd, fl&O_CLOEXEC)<0) goto fail2;
35 f->flags = (f->flags & F_PERM) | f2->flags;