Skip to content

Instantly share code, notes, and snippets.

@bnoordhuis
Created March 17, 2013 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bnoordhuis/05b75296b324f77d8a83 to your computer and use it in GitHub Desktop.
Save bnoordhuis/05b75296b324f77d8a83 to your computer and use it in GitHub Desktop.
Do a binary search for the max RLIMIT_NOFILE.
/* Copyright (c) 2013, Ben Noordhuis <info@bnoordhuis.nl>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/resource.h>
int main(void)
{
struct rlimit lim;
rlim_t lo;
rlim_t hi;
if (getrlimit(RLIMIT_NOFILE, &lim)) {
perror("getrlimit(RLIMIT_NOFILE)");
exit(1);
}
lo = lim.rlim_cur;
hi = lim.rlim_max;
if (hi > 0x1000000)
hi = 0x1000000; /* 16.7m */
/* Do a binary search for the max RLIMIT_NOFILE. */
while (lo + 1 < hi) {
lim.rlim_cur = lo + (hi - lo) / 2;
if (setrlimit(RLIMIT_NOFILE, &lim))
hi = lim.rlim_cur;
else
lo = lim.rlim_cur;
}
if (getrlimit(RLIMIT_NOFILE, &lim)) {
perror("getrlimit(RLIMIT_NOFILE)");
exit(1);
}
printf("RLIMIT_NOFILE=%lld\n", lim.rlim_cur);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment