set errno when fileno is called on a FILE with no underlying fd
authorRich Felker <dalias@aerifal.cx>
Tue, 28 Aug 2018 22:40:15 +0000 (18:40 -0400)
committerRich Felker <dalias@aerifal.cx>
Tue, 28 Aug 2018 22:41:12 +0000 (18:41 -0400)
this is a POSIX requirement.

also remove the gratuitous locking shenanigans and simply access f->fd
under control of the lock. there is no advantage to not doing so, and
it made the correctness non-obvious at best.

src/stdio/fileno.c

index ba7f9391b1ec9baa6023f9a66f569b46a1f85ba2..0bd0e9889eb02b013eb31feea112dd1031bdbc15 100644 (file)
@@ -1,13 +1,16 @@
 #include "stdio_impl.h"
+#include <errno.h>
 
 int fileno(FILE *f)
 {
-       /* f->fd never changes, but the lock must be obtained and released
-        * anyway since this function cannot return while another thread
-        * holds the lock. */
        FLOCK(f);
+       int fd = f->fd;
        FUNLOCK(f);
-       return f->fd;
+       if (fd < 0) {
+               errno = EBADF;
+               return -1;
+       }
+       return fd;
 }
 
 weak_alias(fileno, fileno_unlocked);