在测试c线程guard区域时候的一些疑问。本以为设置了guardsize,线程有了自己的保护内存段了,当访问到这段内存的时候才会由系统内核发出SIGSEGV信号。我的问题是为什么guardsize设置为0了,超出栈大小了也会有SIGSEGV信号?
这个不太懂了。
```c++
#include "iostream"
#include "pthread.h"
#include "unistd.h"
#include "semaphore.h"
#include "signal.h"
#include "errno.h"
#include "stdlib.h"
#include "sys/mman.h"
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while(0)
static char *buffer;
void signal_handler(int sig) {
void *frame_addr = __builtin_frame_address(0);
printf("Got SIGSEGV at address: 0x%lx\n", frame_addr);
exit(EXIT_FAILURE);
}
void *thread_function(void *arg) {
sleep(1);
char p[1];
int i;
for (i = 0; i < 1024; ++i) {
// printf("[%d]\n", i);
printf("[%d] access address: %p\n", i, &p[i * 1024]);
// printf("[%d]\n", i);
p[i * 1024] = 'a';
}
printf("thread_function \n");
}
void main() {
//线程的guard区域同样是PROT_NONE的,如果访问这段内存,同样会使系统内核发出SIGSEGV信号
signal(SIGSEGV, signal_handler);
size_t pagesize = sysconf(_SC_PAGESIZE);
size_t guardsize = pagesize;
size_t stacksize = pagesize;
printf("pagesize:%d\n", pagesize);
char stack_addr[8196];
pthread_attr_t attr_t;
pthread_t tid;
pthread_attr_init(&attr_t);
pthread_attr_setstacksize(&attr_t, stacksize);
pthread_attr_setguardsize(&attr_t, 0);
pthread_attr_setstackaddr(&attr_t, &stack_addr);
pthread_create(&tid, &attr_t, thread_function, NULL);
pthread_attr_getguardsize(&attr_t, &guardsize);
pthread_attr_getstacksize(&attr_t, &stacksize);
printf("guardsize:%d stacksize:%d\n", guardsize, stacksize);
pthread_join(tid, NULL);
}
```