From 7922e2bb776f56b49fd070d3422b41ae1135b95f Mon Sep 17 00:00:00 2001 From: "Andrey A. Chernov" Date: Sat, 26 Jul 2014 08:41:03 +0000 Subject: [PATCH] In the "Too many open files" edge cases don't try to preserve old number for non-std* descriptors, but close old file and retry. Obtained from: inspired by Apple's change from pfg@ MFC after: 2 weeks --- lib/libc/stdio/freopen.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/libc/stdio/freopen.c b/lib/libc/stdio/freopen.c index 28b54f8b0bbe..4dcd50fbb13d 100644 --- a/lib/libc/stdio/freopen.c +++ b/lib/libc/stdio/freopen.c @@ -151,6 +151,14 @@ freopen(const char * __restrict file, const char * __restrict mode, /* Get a new descriptor to refer to the new file. */ f = _open(file, oflags, DEFFILEMODE); + /* If out of fd's close the old one and try again. */ + if (f < 0 && isopen && wantfd > STDERR_FILENO && + (errno == ENFILE || errno == EMFILE)) { + (void) (*fp->_close)(fp->_cookie); + isopen = 0; + wantfd = -1; + f = _open(file, oflags, DEFFILEMODE); + } sverrno = errno; finish: