我需要做一个小 sw 需要保护一个页面进行读/写,然后当访问内存时,它需要增加一个计数器并允许读/写,然后它需要保护内存
我有这段代码,但它导致了无限循环
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
static int alloc_size;
static char* memory;
void segv_handler (int signal_number)
{
printf ("memory accessed!\n");
/* allow read and write */
mprotect (memory, alloc_size, PROT_READ | PROT_WRITE);
/* Protect memory back*/
mprotect (memory, alloc_size, PROT_NONE);
}
int main ()
{
struct sigaction sa;
/* Install segv_handler as the handler for SIGSEGV. */
memset (&sa, 0, sizeof (sa));
sa.sa_handler = &segv_handler;
sigaction (SIGSEGV, &sa, NULL);
alloc_size = 4096;
memory = mmap (0, alloc_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); /* anonymous mapping doesn't need a file desc */
/* Write to the page to obtain a private copy. */
memory[0] = 0;
memory[1] = 0;
/* Make the memory unwritable. */
mprotect (memory, alloc_size, PROT_NONE);
/* Write to the allocated memory region. */
memory[0] = 1; //--> this should trigger the SIGSEGV
memory[1] = 1;
/* All done; unmap the memory. */
printf ("all done\n");
munmap (memory, alloc_size);
return 0;
}