X-Git-Url: http://nsz.repo.hu/git/?p=musl;a=blobdiff_plain;f=src%2Fstdio%2Ffreopen.c;h=c80ce3b438e67e7de275cd2ef1a3a0513d5e05cd;hp=b1f8fe71ba25bcdb72e0b9c963bff494cd16698d;hb=892cafff665b44d238e3b664f61ca38dd965cba6;hpb=2499cd9d9be0ba74e16a6c3dd304e6d69070be35 diff --git a/src/stdio/freopen.c b/src/stdio/freopen.c index b1f8fe71..c80ce3b4 100644 --- a/src/stdio/freopen.c +++ b/src/stdio/freopen.c @@ -7,24 +7,27 @@ /* Locking is not necessary because, in the event of failure, the stream * passed to freopen is invalid as soon as freopen is called. */ -FILE *freopen(const char *filename, const char *mode, FILE *f) +int __dup3(int, int, int); + +FILE *freopen(const char *restrict filename, const char *restrict mode, FILE *restrict f) { - int fl; + int fl = __fmodeflags(mode); FILE *f2; fflush(f); if (!filename) { - f2 = fopen("/dev/null", mode); - if (!f2) goto fail; - fl = syscall(SYS_fcntl, f2->fd, F_GETFL, 0); - if (fl < 0 || syscall(SYS_fcntl, f->fd, F_SETFL, fl) < 0) - goto fail2; + if (fl&O_CLOEXEC) + __syscall(SYS_fcntl, f->fd, F_SETFD, FD_CLOEXEC); + fl &= ~(O_CREAT|O_EXCL|O_CLOEXEC); + if (syscall(SYS_fcntl, f->fd, F_SETFL, fl) < 0) + goto fail; + return f; } else { f2 = fopen(filename, mode); if (!f2) goto fail; - if (syscall(SYS_dup2, f2->fd, f->fd) < 0) - goto fail2; + if (f2->fd == f->fd) f2->fd = -1; /* avoid closing in fclose */ + else if (__dup3(f2->fd, f->fd, fl&O_CLOEXEC)<0) goto fail2; } f->flags = (f->flags & F_PERM) | f2->flags;