did anyone who knows how to use the sigaltstack in a real signal handler program,a simple but complete code may be great help to me! thank you in advance!
#define _GNU_SOURCE
#include
#include
#include
#include
#include
static void handler(int signo)
{
int x;
if(signo == SIGSEGV)
{
printf("Waoh, caught signal %s\n",strsignal(signo));
printf("Top of stack is near %10p", (void*)&x);
}
_exit(EXIT_FAILURE);
}
static void overflowStack(int i)
{
char a[8964];
printf("(%d) Called overflow function. The top of stack is near %10p\n",i ,&a[0]);
overflowStack(i+1);
}
int main(int argc, char *argv[])
{
/*(1)specify that the signal handler will be allocated onto the
alternate signal stack*/
stack_t sigstack;
//malloc return the pointer to the allocated memory on success
//malloc return NULL on error
sigstack.ss_sp = malloc(SIGSTKSZ);
if( sigstack.ss_sp == NULL)
{
printf("Err: malloc error\n");
exit(EXIT_FAILURE);
}
sigstack.ss_size = SIGSTKSZ;
sigstack.ss_flags = 0;
/*(2)Specify that the signal handler will be allocated on the alternate
signal stack */
if(sigaltstack(&sigstack, NULL) == -1)
{
printf("Err: sigaltstack error\n");
exit(EXIT_FAILURE);
}
// sbrk() change the location of the program break, which defines the end of the process's data segment
//On success, sbrk() returns the previous program break.
printf("Now the alternate signal stack is successfully allocated\n");
printf("The address of signal stack is : %10p - %10p\n",sigstack.ss_sp,(char*)sbrk(0)-1);
/*(3)define a struct sigaction to deal with the SIGSEGV*/
struct sigaction act;
act.sa_flags = SA_ONSTACK;
sigemptyset(&act.sa_mask);
act.sa_handler = handler;
sigaction(SIGSEGV, &act, NULL);
overflowStack(1);
}