#include /* for mmap */ #include /* for exit */ #include /* for fprintf */ #include /* for strerror */ #include /* for fork */ #include /* for errno */ #include "mem.h" #define NAME_MAX 64 int parse_args(int argc, char *argv[ ], int *np){ if ( (argc != 2) || ((*np = atoi (argv[1])) <= 0) ) { fprintf (stderr, "Usage: %s nprocs\n", argv[0]); return(-1); }; return(0); } int main(int argc, char *argv[]){ int fd, i, nprocs, *count; pid_t child; void *start_addr; char self[NAME_MAX]; size_t size = sizeof(int); if(parse_args(argc, argv, &nprocs) < 0) exit(EXIT_FAILURE); /* does the file exist (and is the right size)? if not make it! */ if(init_shared_file(&fd, "sharedFile", size) != 0){ exit(EXIT_FAILURE); } /* map it to memory */ start_addr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if(start_addr == MAP_FAILED){ perror("mmap failed"); exit(EXIT_FAILURE); } fprintf(stderr, "mmap returned %ld\n", (long)start_addr); count = (int *)start_addr; *count = 0; for(i = 0; i < nprocs; i++){ child = fork(); if(child < 0){ fprintf(stderr, "%s: fork failed -- %s\n", argv[0], strerror(errno)); exit(EXIT_FAILURE); } if(child > 0) break; } /* name myself */ sprintf(self, "process %d", i); while(1){ count = (int *)start_addr; fprintf(stderr, "%s: count before = %d\n", self, *count); (*count)++; sleep(1); fprintf(stderr, "%s: count after = %d\n", self, *count); } exit(EXIT_SUCCESS); }