4

在启动用 C 编写的程序之前,我必须运行命令“ulimit -n 400”来提高允许打开文件的数量,但是有没有办法在 C 程序中执行等效操作?

也就是说,增加该进程允许打开的文件描述符的数量。(我对每个线程的限制不感兴趣。)

它会涉及设置 ulimits,然后分叉一个允许有更多打开文件的孩子吗?

当然,我可以编写一个运行 ulimit 的 shell 包装器,然后启动我的 C 程序,但感觉不太优雅。我还可以通过 bash 或 sh 的源代码 grep 看看它是如何在那里完成的 - 如果我在这里没有得到答案,也许我会这样做。

同样相关的是,如果您想在很多文件描述符上进行选择,请查看此处

4

2 回答 2

11

我认为您正在寻找setrlimit(2).

于 2010-11-02T10:47:16.343 回答
8
#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;
}
于 2010-11-02T11:01:14.393 回答