open() creates a new file even if it fails with EMFILE

Christian Franke via Cygwin <[email protected]> Mon, 4 May 2026 20:39:36 +0200
Newsgroups gmane.os.cygwin
Message-ID <[email protected]>
Could be reproduced with 3.6.9 and current HEAD.

Testcase:

$ uname -r # or 3.6.9-1.x86_64
3.7.0-0.483.ga1f347c0d5b8.x86_64

$ cat openmany.c
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>

int main()
{
   for (int i = 0; i < 10000; i++) {
     char name[32];
     snprintf(name, sizeof(name), "file-%04d.tmp", i);
     errno = 0;
     int fd = open(name, O_WRONLY | O_CREAT | O_EXCL, 0666);
     if (fd >= 0)
       continue;
     printf("open(%s, ...)=%d (errno=%d)\n", name, fd, errno);
     struct stat st;
     printf("stat(%s, ...)=%d\n", name, stat(name, &st));
     break;
   }
   return 0;
}

$ gcc -o openmany openmany.c

$ ls file-*.tmp
ls: cannot access 'file-*.tmp': No such file or directory

$ ulimit -n
3200

$ ./openmany
open(file-3197.tmp, ...)=-1 (errno=24)
stat(file-3197.tmp, ...)=0

$ ls file-*.tmp
file-0000.tmp
file-0001.tmp
...
file-3195.tmp
file-3196.tmp
file-3197.tmp

$ grep -w 24 /usr/include/sys/errno.h
#define EMFILE 24       /* File descriptor value too large */


Looks like the fd is allocated too late.

-- 
Regards,
Christian


-- 
Problem reports:      https://cygwin.com/problems.html
FAQ:                  https://cygwin.com/faq/
Documentation:        https://cygwin.com/docs.html
Unsubscribe info:     https://cygwin.com/ml/#unsubscribe-simple