how to dynamically increase the stack size of a process
Hi I am trying to implement a process, which increases its available stack dynamically by handling the exception of (overflow/segmentation fault).
I am writing a sample program here, by recursively allocating space on stack and hence growing the stack till it gives a SIGSEGV, I am handling this exception in a handler and increasing the resource limit of the process by using getrlimit and setrlimit, this doesnt seem to work and I cant figure out why, if I try to do the same by programtically generating a SIGSEGV by raise(), I am able to increase the stack size ,here is the code I am using
#include<unistd.h>
#include<sys/resource.h>
#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<sys/time.h>
void allocate(void);
void handler(int sig)
{
struct rlimit r;
getrlimit(RLIMIT_STACK,&r);
r.rlim_cur=r.rlim_cur *5; // increasing stack size five times
setrlimit(RLIMIT_STACK,&r);
write(1,"Handler",7); //to check handler invocation
//signal(SIGSEGV,SIG_DFL);
}
int cntz=0xfff; //for adusting recursion
int main()
{
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags=0;
sa.sa_handler=handler;
sigaction(SIGSEGV,&sa,NULL);
//raise(SIGSEGV); to raise self signal to increase stack size
allocate();
//getchar();
exit(1);
}
void allocate()
{
char staczzk[5000]; //allocating memory on stack in each
recursive call
cntz--;
printf("%dn",cntz);
if (cntz==0)
return;
allocate(); //recusrive call
}
Your signal handler will, by default, use the same stack as the rest of the program, and there's no stack space left thanks to all the calls to allocate
.
The fix is to use an alternate signal stack. The following is based on your code along with code from the sigaltstack man page:
int main()
{
struct sigaction sa;
stack_t ss;
ss.ss_sp = malloc(SIGSTKSZ);
if (ss.ss_sp == NULL) { perror("malloc"); exit(1); }
ss.ss_size = SIGSTKSZ;
ss.ss_flags = 0;
if (sigaltstack(&ss, NULL) == -1) { perror("sigaltstack"); exit(1); }
sigemptyset(&sa.sa_mask);
sa.sa_flags=SA_ONSTACK;
sa.sa_handler=handler;
if(sigaction(SIGSEGV,&sa,NULL)<0) { perror("sigaction"); exit(1); }
//raise(SIGSEGV); to raise self signal to increase stack size
allocate();
exit(1);
}
链接地址: http://www.djcxy.com/p/14098.html
上一篇: 为什么我们需要C ++中的虚函数?
下一篇: 如何动态增加进程的堆栈大小