如何多次更改核心文件大小限制?

How to change core file size limit multiple times?

我想多次更改核心文件大小。我使用以下代码:

#include <errno.h>
#include <iostream>
#include <string.h>
#include <sys/prctl.h>
#include <sys/resource.h>

void SetNewCoreSizeLimit(unsigned new_size) {
  rlimit resource_limit;
  resource_limit.rlim_cur = resource_limit.rlim_max = static_cast<rlim_t>(new_size);

  if (setrlimit(RLIMIT_CORE, &resource_limit) == -1) {
    std::cerr << strerror(errno) << std::endl;
  }  
}

int main() {
  SetNewCoreSizeLimit(5);
  SetNewCoreSizeLimit(10);

  return 0;
}

setrlimit 第一次调用成功,第二次打印失败"Operation not permitted"。为什么?

仔细阅读setrlimit(2):

Each resource has an associated soft and hard limit.

你正在改变两个。一旦设置了 hard 限制,你就不能 raise 它(在普通过程中):

EPERM An unprivileged process tried to raise the hard limit; the CAP_SYS_RESOURCE capability is required to do this.

EINVAL The value specified in resource is not valid; or, for setrlimit() or prlimit(): rlim->rlim_cur was greater than rlim->rlim_max.

您可能应该设置 限制:

 resource_limit.rlim_cur = static_cast<rlim_t>(new_size);
 resource_limit.rlim_max = RLIM_INFINITY;

或者用getrlimit查询之前的限制并保留其.rlim_max字段。

并且您的 shell 可能已经设置了一些限制(例如,通过在 ~/.bashrc 中使用 ulimit)。

您可以尝试 cat /proc/self/limits 在您的 shell 中查询您的限制(以可理解的、文本的、时尚的方式)

请注意,具有根访问权限的用户仍然可以使用 gcore(1) anyway (or use proc(5)/proc/$(pidof yourapp)/maps/proc/$(pidof yourapp)/mem 等...来获取进程中的数据)