1 #include "stdio_impl.h"
2 #include <fcntl.h>
3 #include <unistd.h>
4
5 /* The basic idea of this implementation is to open a new FILE,
6 * hack the necessary parts of the new FILE into the old one, then
7 * close the new FILE. */
8
9 /* Locking IS necessary because another thread may provably hold the
10 * lock, via flockfile or otherwise, when freopen is called, and in that
11 * case, freopen cannot act until the lock is released. */
12
freopen(const char * restrict filename,const char * restrict mode,FILE * restrict f)13 FILE *freopen(const char *restrict filename, const char *restrict mode, FILE *restrict f)
14 {
15 int file_flags = 0;
16 int fl = __fmodeflags(mode, &file_flags);
17 FILE *f2;
18
19 FLOCK(f);
20
21 fflush(f);
22
23 if (!filename) {
24 if (fl&O_CLOEXEC)
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)
28 goto fail;
29 } else {
30 f2 = fopen(filename, mode);
31 if (!f2) goto fail;
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;
34
35 f->flags = (f->flags & F_PERM) | f2->flags;
36 f->read = f2->read;
37 f->readx = f2->readx;
38 f->write = f2->write;
39 f->seek = f2->seek;
40 f->close = f2->close;
41
42 fclose(f2);
43 }
44
45 f->mode = 0;
46 f->locale = 0;
47 FUNLOCK(f);
48 return f;
49
50 fail2:
51 fclose(f2);
52 fail:
53 fclose(f);
54 return NULL;
55 }
56
57 weak_alias(freopen, freopen64);
58