如何执行“ulimit -n 400”的等效操作从C内部?

发布于 2024-09-30 14:06:52 字数 440 浏览 12 评论 0原文

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

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

是否会涉及设置 ulimit,然后分叉一个允许有更多打开文件的子进程?

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

同样相关的是,如果您想选择大量文件描述符,看这里

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浮生未歇 2024-10-07 14:06:52

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

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

缘字诀 2024-10-07 14:06:52
#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;
}
#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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文