Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do the equivalent of "ulimit -n 400" from within C?

I must run the command "ulimit -n 400" to raise number of allowed open files before I start my program written in C, but is there a way to do the equivalent from within the C program?

That is, increase the number of allowed open file descriptors for that process. (I am not interested in per thread limits.)

Will it involve setting ulimits, then forking a child which will be allowed to have more open files?

Of course, I could write a shell wrapper which runs ulimit, then start my C program, but it feels less elegant. I could also grep through the source code of bash or sh to see how it is done there - maybe I will if I get no answer here.

Also related, if you want to select on a lot of file descriptors, look here.

like image 991
Prof. Falken Avatar asked Dec 01 '22 04:12

Prof. Falken


2 Answers

I think that you are looking for setrlimit(2).

like image 181
D.Shawley Avatar answered Dec 04 '22 06:12

D.Shawley


#include <sys/resource.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main (int argc, char *argv[])
{
  struct rlimit limit;
  
  limit.rlim_cur = 65535;
  limit.rlim_max = 65535;
  if (setrlimit(RLIMIT_NOFILE, &limit) != 0) {
    printf("setrlimit() failed with errno=%d\n", errno);
    return 1;
  }

  /* Get max number of files. */
  if (getrlimit(RLIMIT_NOFILE, &limit) != 0) {
    printf("getrlimit() failed with errno=%d\n", errno);
    return 1;
  }

  printf("The soft limit is %lu\n", limit.rlim_cur);
  printf("The hard limit is %lu\n", limit.rlim_max);

  /* Also children will be affected: */
  system("bash -c 'ulimit -a'");

  return 0;
}
like image 34
Prof. Falken Avatar answered Dec 04 '22 04:12

Prof. Falken