--- /dev/null
+/***************************************************************
+ *
+ * File SharedMem.c
+ * Routine for Shared Memory use
+ *
+ * Author: S. Piccardi
+ *
+ * $Id: SharedMem.c,v 1.1 2002/12/03 11:06:05 piccardi Exp $
+ *
+ ***************************************************************/
+#include <sys/shm.h> /* SysV IPC shared memory declarations */
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdio.h> /* standard I/O functions */
+#include <fcntl.h>
+#include <signal.h> /* signal handling declarations */
+/*
+ * Function ShmCreate:
+ * Create and attach a SysV shared memory segment to the current process.
+ *
+ * First call get a shared memory segment with KEY key access and size SIZE,
+ * by creating it with R/W privilege for the user (this is the meaning of
+ * the ored flags). The function return an identifier shmid used for any
+ * further reference to the shared memory segment.
+ * Second call attach the shared memory segment to this process and return a
+ * pointer to it (of void * type).
+ * Then initialize shared memory to the given value
+ *
+ * Input: an IPC key value
+ * the shared memory segment size
+ * Return: the address of the segment
+ */
+void * ShmCreate(key_t ipc_key, int shm_size, char fill)
+{
+ void * shptr;
+ int shmid; /* ID of the IPC shared memory segment */
+ shmid = shmget(ipc_key,shm_size,IPC_CREAT|0666); /* get shm ID */
+ if (shmid < 0) {
+ return (void *) shmid;
+ }
+ shptr = shmat(shmid,0,0); /* take the pointer to it */
+ if ( shptr == 0 ){
+ perror("cannot attach shared memory");
+ exit(1);
+ }
+ memset((void *)shptr, fill, shm_size); /* second counter starts from "0" */
+ return shptr;
+}
+/*
+ * Function ShmFind:
+ * Find a shared memory segment
+ * Input: an IPC key value
+ * the shared memory segment size
+ * Return: the address of the segment
+ */
+void * ShmFind(key_t ipc_key, int shm_size)
+{
+ void * shptr;
+ int shmid; /* ID of the IPC shared memory segment */
+ if ( (shmid=shmget(ipc_key,shm_size,0))<0 ){ /* find shared memory ID */
+ perror("cannot find shared memory");
+ exit(1);
+ }
+ if ( (shptr=shmat(shmid,0,0)) < 0 ){ /* take the pointer to it */
+ perror("cannot attach shared memory");
+ exit(1);
+ }
+ return shptr;
+}