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

11,331

Solution 1

#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;
}

Solution 2

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

Share:
11,331
Prof. Falken
Author by

Prof. Falken

Updated on June 28, 2022

Comments

  • Prof. Falken
    Prof. Falken almost 2 years

    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.