使用setrlimit增加Linux中的堆栈大小

在阅读有关如何在ggn编译的c ++应用程序中增加堆栈大小的信息时,我了解到可以在程序开始时使用setrlimit完成此操作。但是,我找不到任何成功的示例来说明如何使用它,以及在程序的哪一部分应用它以获得c ++程序的64M堆栈大小,有人可以帮助我吗?



侃侃无极
浏览 1122回答 3
3回答

守候你守候我

通常,您可以main()在调用任何其他函数之前,例如在的开始处及早设置堆栈大小。通常,逻辑为:调用getrlimit以获取当前堆栈大小如果当前大小<所需的堆栈大小,则调用setrlimit以将堆栈大小增加到所需大小在C语言中,可能会这样编码:#include <sys/resource.h>#include <stdio.h>int main (int argc, char **argv){&nbsp; &nbsp; const rlim_t kStackSize = 64L * 1024L * 1024L;&nbsp; &nbsp;// min stack size = 64 Mb&nbsp; &nbsp; struct rlimit rl;&nbsp; &nbsp; int result;&nbsp; &nbsp; result = getrlimit(RLIMIT_STACK, &rl);&nbsp; &nbsp; if (result == 0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (rl.rlim_cur < kStackSize)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rl.rlim_cur = kStackSize;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = setrlimit(RLIMIT_STACK, &rl);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (result != 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fprintf(stderr, "setrlimit returned result = %d\n", result);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // ...&nbsp; &nbsp; return 0;}

米琪卡哇伊

要超出setrlimit中的硬限制(在OSX上默认只有64MB),请使用具有选择的堆栈大小的pthreads创建一个新线程。这是一个C代码段:&nbsp; &nbsp; // Call function f with a 256MB stack.&nbsp; &nbsp; static int bigstack(void *(*f)(void *), void* userdata) {&nbsp; &nbsp; &nbsp; pthread_t thread;&nbsp; &nbsp; &nbsp; pthread_attr_t attr;&nbsp; &nbsp; &nbsp; // allocate a 256MB region for the stack.&nbsp; &nbsp; &nbsp; size_t stacksize = 256*1024*1024;&nbsp; &nbsp; &nbsp; pthread_attr_init(&attr);&nbsp; &nbsp; &nbsp; pthread_attr_setstacksize(&attr, stacksize);&nbsp; &nbsp; &nbsp; int rc = pthread_create(&thread, &attr, f, userdata);&nbsp; &nbsp; &nbsp; if (rc){&nbsp; &nbsp; &nbsp; &nbsp; printf("ERROR: return code from pthread_create() is %d\n", rc);&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; pthread_join(thread, NULL);&nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP