阅读有关如何增加使用gnu编译的c ++应用程序的堆栈大小的信息,在编译时,我知道可以在程序开始时使用setrlimit来完成.然而,我找不到任何关于如何使用它的成功示例以及程序的哪个部分应用它以获得c ++程序的64M堆栈大小,有人可以帮助我吗?
Thanlks
Pau*_*l R 19
通常main(),在调用任何其他函数之前,您应该在开始时尽早设置堆栈大小,例如e,g .通常逻辑是:
在C中可能编码如下:
#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\n", result);
}
}
}
// ...
return 0;
}
Run Code Online (Sandbox Code Playgroud)
wal*_*lyk 10
查看运行时执行最大值是否限制它:
[wally@zf conf]$ ulimit -all
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 16114
max locked memory (kbytes, -l) 32
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 16114
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
Run Code Online (Sandbox Code Playgroud)
请注意,默认情况下,堆栈大小限制为10 MiB.所以将其增加到64 MiB:
[wally@zf conf]$ ulimit -s 64M
-bash: ulimit: 64M: invalid number
[wally@zf conf]$ ulimit -s 65536
[wally@zf conf]$ ulimit -all
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 16114
max locked memory (kbytes, -l) 32
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 65536
cpu time (seconds, -t) unlimited
max user processes (-u) 16114
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
Run Code Online (Sandbox Code Playgroud)
要超越 setrlimit 中的硬限制(在 OSX 上,默认情况下它只有 64MB),请使用 pthreads 创建一个具有您选择的堆栈大小的新线程。这是一个 C 代码片段:
// Call function f with a 256MB stack.
static int bigstack(void *(*f)(void *), void* userdata) {
pthread_t thread;
pthread_attr_t attr;
// allocate a 256MB region for the stack.
size_t stacksize = 256*1024*1024;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, stacksize);
int rc = pthread_create(&thread, &attr, f, userdata);
if (rc){
printf("ERROR: return code from pthread_create() is %d\n", rc);
return 0;
}
pthread_join(thread, NULL);
return 1;
}
Run Code Online (Sandbox Code Playgroud)