Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

Thanlks

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
707 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:

  • call getrlimit to get current stack size
  • if current size < required stack size then
    • call setrlimit to increase stack size to required size

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...