Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 7 Jul 1996 15:34:27 -0400 (EDT)
From:      "Ron G. Minnich" <rminnich@Sarnoff.COM>
To:        hackers@freebsd.org
Subject:   filemalloc etc. for shared memory between processes
Message-ID:  <Pine.SUN.3.91.960707153113.15146A-100000@terra>

next in thread | raw e-mail | index | archive | help
These allow you to set up a shared mapped file for use by multiple
processes in the malloc and calloc style. Tested and used extensively in 
my latest DSM. Comments would be appreciated if I've made mistakes in here!
note that if the file exists it is used.


#include	<stdio.h>
#include        <fcntl.h>
#include        <errno.h>
#include 	<signal.h>
#include        <sys/mman.h>
#include 	<sys/time.h>
#include        <sys/param.h>
#include	<sys/types.h>
#include 	<sys/stat.h>
#include 	<sys/shm.h>
#include	<sys/socket.h>
#include        <sys/ioctl.h>

#include	<netinet/in.h>
#include	<netinet/tcp.h>
#include        <arpa/inet.h>

#include	<netdb.h>
#include        <vm/vm_prot.h>
#define		bcopy(s, d, l)	memcpy(d, s, l)
#define		bzero(b, l)	memset(b, 0, l)
/* this is a simple filemalloc function */
/* first is filemake, then filemap, then filemalloc */

size_t
filesize(int fd)
{
  struct stat buf[1];
  int actualsize = 0;
  if (fstat(fd, buf) == 0)
    {
      actualsize = buf[0].st_size;
    }
  return actualsize;
}

/* 
 */
int
filemake(char *name, size_t size)
{
  static char base[MAXPATHLEN];
  int fd = -1;

  strncpy(base, name, sizeof(base));
  base[MAXPATHLEN-1] = 0; /* paranoia */
  fd = mkstemp(base);

  if ((fd >= 0) && size && (filesize(fd) < size))
    {
      if (ftruncate(fd, (off_t) size))
        perror("ftruncate call in segalloc (MNFS library)");
    }
  return fd;
}   

caddr_t
filemap(fd, va, size, off)
     int fd;
     caddr_t va;
     unsigned long size;
     off_t off;
{
  caddr_t p = NULL;
  int actualsize;
  int flags = MAP_SHARED;
  if (size == 0)
    actualsize = filesize(fd);
   else
     actualsize = size;

  if (va)
    flags |= MAP_FIXED;
  p = mmap(va, actualsize, PROT_WRITE|PROT_READ, flags, fd, off);
  if ((int) p == -1)
    {
      perror("filemap");
      return 0;
    }
  else
    {
      return p;
    }
}   

void *
filemalloc(unsigned int bytes)
{
  int fd;
  void *ptr;
  fd = filemake("/var/tmp/zounds.XXXXXX", bytes);
  if (fd < 0)
    exit_error("filemalloc make");
  ptr = filemap(fd, 0, 0, 0);
  if ((int) ptr < 0)
    zerror("filemalloc map");
  if (! debug)
    (void) close(fd);
  return ptr;
  
}

void *
filecalloc(int nelems, size_t sizeelem)
{
  void *ptr = filemalloc(nelems * sizeelem);
  bzero(ptr, nelems*sizeelem);
  return ptr;
}





Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.SUN.3.91.960707153113.15146A-100000>