使用 setrlimit 在 Linux 中增加堆栈大小堆栈、大小、setrlimit、Linux

2023-09-07 02:48:10 作者:结局是一个人

在编译时阅读有关如何增加使用 gnu 编译的 c++ 应用程序的堆栈大小的信息,我了解到可以在程序开始时使用 setrlimit 来完成.尽管如此,我找不到任何成功的例子来说明如何使用它以及在程序的哪个部分应用它以便为 c++ 程序获得 64M 的堆栈大小,有人可以帮助我吗?

reading information about how to increase stack size for a c++ application compiled with gnu, at compilation time, I understood that it can be done with setrlimit at the beginning of the program. Nevertheless I could not find any successful example on how to use it and in which part of the program apply it in order to get a 64M stack size for a c++ program, could anybody help me?

谢谢

推荐答案

通常你会在早期设置堆栈大小,例如,在 main() 的开头,然后再调用任何其他职能.通常的逻辑是:

Normally you would set the stack size early on, e,g, at the start of main(), before calling any other functions. Typically the logic would be:

调用 getrlimit 以获取当前堆栈大小如果当前大小 那么所需的堆栈大小调用 setrlimit 将堆栈大小增加到所需大小

在 C 中可能会这样编码:

In C that might be coded something like this:

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

int main (int argc, char **argv)
{
    const rlim_t kStackSize = 64L * 1024L * 1024L;   // min stack size = 64 Mb
    struct rlimit rl;
    int result;

    result = getrlimit(RLIMIT_STACK, &rl);
    if (result == 0)
    {
        if (rl.rlim_cur < kStackSize)
        {
            rl.rlim_cur = kStackSize;
            result = setrlimit(RLIMIT_STACK, &rl);
            if (result != 0)
            {
                fprintf(stderr, "setrlimit returned result = %d
", result);
            }
        }
    }

    // ...

    return 0;
}