Is it possible to portably access the maximum number of files that can be simultaneously open within the current process, in C++ (e.g. the result of ulimit -n
on unix systems)? I'm writing an application in C++ that potentially requires hundreds of open files, often more than the systems default maximum. Going over the maximum open file limit generally causes difficult to diagnose crashes, especially as most users are not aware of the limit. If I knew the limit at startup, I could potentially warn the user of potential issues, or give a better error message when things go wrong.
Asked
Active
Viewed 854 times
0

Daniel
- 8,179
- 6
- 31
- 56
-
Define "portable" in terms of target operating systems. – tadman Feb 08 '18 at 19:09
-
At least Linux, OS X, and Windows. – Daniel Feb 08 '18 at 19:11
-
There is `sysconf(_SC_OPEN_MAX)` .. – Jesper Juhl Feb 08 '18 at 19:13
-
POSIX `getrlimit(RLIMIT_NOFILE)` – Barmar Feb 08 '18 at 19:14
-
`#include
` and use the macro `FOPEN_MAX`. – Pete Becker Feb 08 '18 at 19:17 -
[Windows has a rather large limit on open file handles](https://stackoverflow.com/a/4276338/65863) (16384 by default), which you are not likely going to hit in your app. However, C library APIs, like `fopen()`, have much smaller limits (512 by default). See [Is there a limit on number of open files in Windows](https://stackoverflow.com/questions/870173/) – Remy Lebeau Feb 08 '18 at 22:38
1 Answers
2
In POSIX-compatible systems (which I think includes Windows):
#include <sys/resource.h>
struct rlimit lim;
getrlimit(RLIMIT_NOFILE, &lim);
rlim_t max_files = lim.rlim_cur;

Barmar
- 741,623
- 53
- 500
- 612
-
-
@RemyLebeau [Wikipedia](https://en.wikipedia.org/wiki/POSIX#POSIX_for_Microsoft_Windows) says "Windows C Runtime Library and Windows Sockets API implement commonly used POSIX API functions for file, time, environment, and socket access,[33] although the support remains largely incomplete and not fully interoperable with POSIX-compliant implementations." – Barmar Feb 08 '18 at 22:38
-
Having a few POSIX-compatible functions does not make it a POSIX system – Remy Lebeau Feb 08 '18 at 22:39
-
-
Windows itself doesn't have a `getrlimit()` function, so I suppose it would depend on which vendor's C library implementation you are using. – Remy Lebeau Feb 08 '18 at 22:51