#ifndef _Mmap_include
#define _Mmap_include

/* package to help translate from the relatively standard use of mmap
   in Unix to the Linux version where the file descriptor cannot be -1 
*/
/* Include file by Henry M. Walker, October 7, 2000 */
/* File:  /home/walker/c/concurrency-linux/Mmap-include.c */

#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

/* set up shared memory segment */
caddr_t Mmap (void  *start,  size_t len, int prot , int flags, 
              int fd, off_t offset) 
{  FILE * f;
   caddr_t shared_memory;   /* shared memory base address */
   int i;       /* loop index */

   /* use C's standard mmap procedure as long as file descriptor fd
      is not -1 */
   if (fd != -1)
     return mmap (start, len, prot, flags, fd, offset);

   /* when fd is -1, mmap on Linux requires a file descriptor for a file
      of length at least if size len, the size of the shared memory segnment
   */

   /* create file of required length, initialized to null characters
   */
   printf ("Note:  creating file 'abcde-3.141592-temp.file.tmp' for memory map\n");
   f = fopen ("abcde-3.141592-temp.file.tmp", "w");
   for (i=0; i<len+(int)start+(int)offset; i++) 
     fputc ('\0', f);
   fclose (f);

   /* open file for reading and writing, for binding to shared memory */
   fd = open ("abcde-3.141592-temp.file.tmp", O_RDWR);
   if (fd  < 0) {
     perror ("open error");  
     exit (1); 
   }

   /* map shared memory; Linux does not allow flags above 31*/
   shared_memory=mmap(start, len, prot, flags & 31, fd, offset);
   if (shared_memory == (caddr_t) -1)
     { perror ("error in mmap while allocating shared memory\n");
       exit (1);
     }

   close (fd);

   return (shared_memory);
}

#endif
