Мне нужно сделать небольшой 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;
}