How to fill up virtual memory space in linux with only using a single image file?

So I am stuck here... I've tried using mmap() but it won't hold the files into memory unless they are being used by something I believe? Here is the code:

/* For the size of the file. */
#include <sys/stat.h>
/* This contains the mmap calls. */
#include <sys/mman.h>
/* These are for error printing. */
#include <errno.h>
#include <string.h>
#include <stdarg.h>
/* This is for open. */
#include <fcntl.h>
#include <stdio.h>
/* For exit. */
#include <stdlib.h>
/* For the final part of the example. */
#include <ctype.h>
/* "check" checks "test" and prints an error and exits if it is
true. */
static void
check (int test, const char * message, ...)
{
if (test) { va_list args; va_start (args, message); vfprintf (stderr, message, args); va_end (args); fprintf (stderr, "\n"); exit (EXIT_FAILURE);
}
}
int main ()
{
/* The file descriptor. */
int fd;
/* Information about the file. */
struct stat s;
int status;
size_t size;
/* The file name to open. */
const char * file_name = "MentalClarity.png";
/* The memory-mapped thing itself. */
const char * mapped[200000];
int i;
int j;
/* Open the file for reading. */
fd = open ("me.c", O_RDONLY);
check (fd < 0, "open %s failed: %s", file_name, strerror (errno));
/* Get the size of the file. */
status = fstat (fd, & s);
check (status < 0, "stat %s failed: %s", file_name, strerror (errno));
size = s.st_size;
/* Memory-map the file. */
for(j=1;j<=200000;j++){
mapped[j] = mmap (NULL, size, PROT_READ, 0, fd, 0);
check (mapped == MAP_FAILED, "mmap %s failed: %s", file_name, strerror (errno));
}
int value=0;
while(value!=1){
printf("Enter 1 to exit");
scanf("%d",&value);
}
return 0;
}

I am just trying to fill up my swap space with one image file, if this is even possible? Thank you in advance.

1 Answer

Ubuntu avoids using swap unless it needs the memory. You can just keep allocating and filling memory until it needs to be paged out. You don't need to hit every byte, just a least one byte in every page. You could use a loop where you allocate a page of memory and write to it in a loop to fill memory.

Using mmap maps the file into the virtual memory image of the application. Any paging activity for the mmapped memory will use the file rather than swap.

You may be able to do the same by writing a large file to /tmp if you are using tmpfs as its file system.

Modern operating systems allow you to over-commit virtual memory. This allows use of space memory structures that far exceed available memory.

5

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like