freopen.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "stdio_impl.h"
  2. #include <fcntl.h>
  3. /* The basic idea of this implementation is to open a new FILE,
  4. * hack the necessary parts of the new FILE into the old one, then
  5. * close the new FILE. */
  6. /* Locking IS necessary because another thread may provably hold the
  7. * lock, via flockfile or otherwise, when freopen is called, and in that
  8. * case, freopen cannot act until the lock is released. */
  9. int __dup3(int, int, int);
  10. FILE *freopen(const char *restrict filename, const char *restrict mode, FILE *restrict f)
  11. {
  12. int fl = __fmodeflags(mode);
  13. FILE *f2;
  14. FLOCK(f);
  15. fflush(f);
  16. if (!filename) {
  17. if (fl&O_CLOEXEC)
  18. __syscall(SYS_fcntl, f->fd, F_SETFD, FD_CLOEXEC);
  19. fl &= ~(O_CREAT|O_EXCL|O_CLOEXEC);
  20. if (syscall(SYS_fcntl, f->fd, F_SETFL, fl) < 0)
  21. goto fail;
  22. } else {
  23. f2 = fopen(filename, mode);
  24. if (!f2) goto fail;
  25. if (f2->fd == f->fd) f2->fd = -1; /* avoid closing in fclose */
  26. else if (__dup3(f2->fd, f->fd, fl&O_CLOEXEC)<0) goto fail2;
  27. f->flags = (f->flags & F_PERM) | f2->flags;
  28. f->read = f2->read;
  29. f->write = f2->write;
  30. f->seek = f2->seek;
  31. f->close = f2->close;
  32. fclose(f2);
  33. }
  34. FUNLOCK(f);
  35. return f;
  36. fail2:
  37. fclose(f2);
  38. fail:
  39. fclose(f);
  40. return NULL;
  41. }
  42. LFS64(freopen);