http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48587
Summary: Avoid exhausting unit number with NEWUNIT= Product: gcc Version: unknown Status: UNCONFIRMED Severity: enhancement Priority: P3 Component: libfortran AssignedTo: unassig...@gcc.gnu.org ReportedBy: j...@gcc.gnu.org As was recently pointed out by Tobias Burnus in a thread on comp.lang.fortran, the current implementation of NEWUNIT= doesn't reuse unit numbers. Hence it's possible that a program might exhaust the available unit numbers (this requires that the program repeatedly closes and reopens files, as OS's have limits on the number of file descriptors a process may have concurrently opened, typically 1024 or something like that) Currently there is just a (mutex protected) static variable which is decremented for each time an OPEN statement with NEWUNIT= is issued, with a wraparound check that generates an error if wraparound is detected. IMHO an elegant solution would be to just reuse the kernel provided file descriptor. E.g. int fd = open(...); if (fd == -1) { /* Handle error... */ } new_unit_number = -fd; This should work because a successful open() will always return a positive fd number (see http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html ), and the kernel takes care of reusing file descriptor numbers of closed files.