Skip to content

Instantly share code, notes, and snippets.

@siers
Created January 19, 2013 12:26
Show Gist options
  • Save siers/4572415 to your computer and use it in GitHub Desktop.
Save siers/4572415 to your computer and use it in GitHub Desktop.
mmap for darwin and linux(might work on some other platforms too)
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>
#include <sys/mman.h>
#define SHMLEN sizeof(int) * 2
#define TIMES 30
#define SEC(x) ((int) (x * 1000000))
int* mem;
enum { VALUE, COUNTER };
/* Fork. */
void
x()
{
while (mem[COUNTER] > 0) {
mem[VALUE]++;
mem[COUNTER]--;
usleep(SEC(0.3));
}
}
/* Original process. */
void
y()
{
while (mem[COUNTER] > 0) {
printf("*memory = %i\n", mem[VALUE]);
usleep(SEC(1));
}
}
void
fini()
{
munmap(mem, SHMLEN);
}
int
main()
{
int fd = -1;
int flags = MAP_SHARED;
/* http://lists.gnu.org/archive/html/bug-gnulib/2005-09/msg00124.html */
#ifdef MAP_ANON
flags |= MAP_ANON;
#else
assert((fd = open("/dev/zero", O_RDWR)) != -1);
#endif
assert((mem = mmap(0, SHMLEN, PROT_READ | PROT_WRITE,
flags, fd, 0)) != 0);
mem[COUNTER] = TIMES;
if (fork()) x(); else y();
atexit(fini);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment