Skip to content

Instantly share code, notes, and snippets.

@fakedrake
Created October 16, 2012 23:55
Show Gist options
  • Save fakedrake/3902868 to your computer and use it in GitHub Desktop.
Save fakedrake/3902868 to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define CONSUMER_ERROR(msg) \
do {perror("Consumer Error: " msg "\n"); exit(1); }while(0)
#define PRODUCER_ERROR(msg) \
do {perror("Producer Error: " msg "\n"); exit(1); }while(0)
#define PRODUCER_PRINT(format, ...) printf ("<<Producer>> (pid: %d): " format "\n", getpid(), ##__VA_ARGS__ )
#define CONSUMER_PRINT(format, ...) printf ("<<Consumer>> (pid: %d): " format "\n", getpid(), ##__VA_ARGS__ )
#define SHM_NAME "/my_sharedmem"
#define STACK_SIZE 1000
void producer();
void consumer();
int fd_err_handle(int);
int main(int argc, char *argv[])
{
pid_t pID = fork();
if (pID == 0) {
// Code only executed by child process
printf ("Child is born\n");
consumer();
} else if (pID < 0) {
perror("Unable to fork\n");
exit(1);
} else {
// Code only executed by parent process
printf ("Parent surivived\n");
producer();
}
return 0;
}
void producer()
{
int fd, d;
unsigned* spool, optimizable1;
PRODUCER_PRINT("started");
fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO);
if (fd<0) {
PRODUCER_ERROR("Failed to open shared memory.");
exit(1);
}
ftruncate(fd, sizeof(unsigned));
PRODUCER_PRINT("memory file opened");
spool = mmap(NULL, sizeof(unsigned), PROT_WRITE|PROT_EXEC, MAP_SHARED, fd, 0);
PRODUCER_PRINT("mmaped to %p", spool);
perror("<<Producer>>");
/* Write and flush to the pool. */
for (d=0; d<STACK_SIZE; d++) {
*spool = d;
msync(spool, sizeof(unsigned), MS_SYNC | MS_INVALIDATE);
}
PRODUCER_PRINT("ended");
}
void consumer()
{
unsigned* spool;
int fd, read, tmp, d, top = 0;
unsigned stack[STACK_SIZE];
CONSUMER_PRINT("started");
fd = shm_open(SHM_NAME, O_RDONLY, 0);
if (fd < 0) {
CONSUMER_ERROR("Failed to open shared memory.");
exit(1);
}
CONSUMER_PRINT("memory file opened");
spool = mmap(NULL, sizeof(unsigned), PROT_READ, MAP_SHARED, fd, 0);
perror("<<Consumer>>");
CONSUMER_PRINT("mmaped to %p", spool);
/* Read the pool many many times. */
for (d=0; d<STACK_SIZE; d++) {
tmp = *spool;
stack[top] = tmp;
read = tmp;
top = (top+1);
}
CONSUMER_PRINT( "Distinct numbers tracked: %d", top);
for (d=0; d<top; d++) {
printf("\t%d\n", stack[d]);
}
CONSUMER_PRINT("ended");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment