#include #include #include #include /* * This program allocates physical memory and holds it. Its primary purpose is to * reduce the available memory on the machine in order to test how other programs * deal with low memory conditions. * * The mmap call creates the memory regions, and mlock locks the memory pages to physical * RAM. Memory is allocated into small pieces to make sure that we don't have trouble * with address space fragmentation. */ /* 64mb allocation size */ #define CHUNK_SIZE (1024*1024*64) int main( int argc, char** argv ) { if( argc < 2 ) { fprintf( stderr, "You need to specify an amount of memory, in megabytes.\n" ); } size_t length = atol( argv[1] ); length *= 1024 * 1024; int result; size_t chunk; void* mapping; while( length > 0 ) { if( CHUNK_SIZE < length ) { chunk = CHUNK_SIZE; } else { chunk = length; } mapping = mmap( 0, chunk, PROT_WRITE | PROT_READ, MAP_ANON | MAP_SHARED, 0, 0 ); if( mapping == (void*)-1 ) perror( "Couldn't map some of the memory." ); result = mlock( mapping, chunk ); if( result < 0 ) perror( "Couldn't lock some pages." ); printf( "# %zdMB (%zdMB left)\n", chunk / (1024*1024), (length - chunk) / (1024*1024) ); fflush(stdout); length -= chunk; } printf( "Memory locked.\n" ); // wait for someone to kill the process while (1) sleep(1000); }