#include <unistd.h>
#include <sys/mman.h>
#include <stdio.h>
#define DATA_SIZE 1024
lock_memory(char *addr, size_t size) {
unsigned long page_offset, page_size;
page_size = sysconf(_SC_PAGE_SIZE);
page_offset = (unsigned long) addr % page_size;
addr -= page_offset; /* Adjust addr to page boundary */
size += page_offset; /* Adjust size with page_offset */
return ( mlock(addr, size) ); /* Lock the memory */
}
unlock_memory(char *addr, size_t size){
unsigned long page_offset, page_size;
page_size = sysconf(_SC_PAGE_SIZE);
page_offset = (unsigned long) addr % page_size;
addr -= page_offset; /* Adjust addr to page boundary */
size += page_offset; /* Adjust size with page_offset */
return ( munlock(addr, size) ); /* Unlock the memory */
}
main() {
char data[DATA_SIZE];
int ret;
if ( lock_memory(data, DATA_SIZE) == -1 ) { perror("lock_memory"); }
#Una vez tenemos garantizado que la memoria ira a la RAM metemos datos
ret = sprintf(data, "UnPasswordMegaSecreto");
printf ("Mi password mega secreto %s\\n", data) ;
if ( unlock_memory(data, DATA_SIZE) == -1 )
perror("unlock_memory");
}