Skip to content

Instantly share code, notes, and snippets.

@amriunix
Created November 1, 2017 23:13
Show Gist options
  • Save amriunix/5f67929b5f357ae673e597f5777ca685 to your computer and use it in GitHub Desktop.
Save amriunix/5f67929b5f357ae673e597f5777ca685 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc,char *argv[])
{
struct stat st;
char content[17];
char *new_content = "***New Content***";
void *map;
// Opening the file in read and write mode (O_RDWR)
// Need to match exacly the PROT argument in the mmap function!
int f=open(argv[1], O_RDWR);
fstat(f, &st);
// Map the file to memory
// NULL = the kernel wil choose the address at which he will create the mapping
// PROT_READ | PROT_WRITE (PROT argument)!
// MAP_SHARED = Share this mapping. Updates to the mapping are visible to other processes that map this file
map=mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, f, 0);
// Read from the file via the mapped memory
memcpy(content, map, 17);
content[17] = '\0';
printf("read: %s\n", content);
// Write to the file via the mapped memory
memcpy(map, new_content, strlen(new_content));
// Clean up to save changes!
munmap(map, st.st_size);
close(f);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment