Skip to content

Instantly share code, notes, and snippets.

@chrisdew
Created June 13, 2012 14:28
Show Gist options
  • Save chrisdew/2924412 to your computer and use it in GitHub Desktop.
Save chrisdew/2924412 to your computer and use it in GitHub Desktop.
attempt at copy-on-write, fails with "bus error"
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZE 4096
int main(void) {
int fd = shm_open("/tmpmem", O_RDWR | O_CREAT, 0666);
int r = ftruncate(fd, SIZE);
printf("fd: %i, r: %i\n", fd, r);
char *buf = mmap(NULL, SIZE, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
printf("debug 0\n");
buf[SIZE - 2] = 41;
buf[SIZE - 1] = 42;
printf("debug 1\n");
// don't know why this is needed, but it's in the answer
//r = mmap(buf, SIZE, PROT_READ | PROT_WRITE,
// MAP_FIXED, fd, 0);
//printf("r: %i\n", r);
char *buf2 = mmap(NULL, SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE, fd, 0);
printf("buf2: %i\n", buf2);
buf2[SIZE - 1] = 43;
buf[SIZE - 2] = 40;
printf("buf[-2]: %i, buf[-1]: %i, buf2[-2]: %i, buf2[-1]: %i\n",
buf[SIZE - 2],
buf[SIZE - 1],
buf2[SIZE - 2],
buf2[SIZE - 1]);
unlink(fd);
return EXIT_SUCCESS;
}
@chrisdew
Copy link
Author

Produces:

fd: 3, r: 0
debug 0
debug 1
buf2: -370720768
buf[-2]: 40, buf[-1]: 42, buf2[-2]: 41, buf2[-1]: 43

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment