1 /***************************************************************
4 * Routine for Shared Memory use
8 * $Id: SharedMem.c,v 1.1 2002/12/03 11:06:05 piccardi Exp $
10 ***************************************************************/
11 #include <sys/shm.h> /* SysV IPC shared memory declarations */
12 #include <sys/types.h>
14 #include <stdio.h> /* standard I/O functions */
16 #include <signal.h> /* signal handling declarations */
19 * Create and attach a SysV shared memory segment to the current process.
21 * First call get a shared memory segment with KEY key access and size SIZE,
22 * by creating it with R/W privilege for the user (this is the meaning of
23 * the ored flags). The function return an identifier shmid used for any
24 * further reference to the shared memory segment.
25 * Second call attach the shared memory segment to this process and return a
26 * pointer to it (of void * type).
27 * Then initialize shared memory to the given value
29 * Input: an IPC key value
30 * the shared memory segment size
31 * Return: the address of the segment
33 void * ShmCreate(key_t ipc_key, int shm_size, char fill)
36 int shmid; /* ID of the IPC shared memory segment */
37 shmid = shmget(ipc_key,shm_size,IPC_CREAT|0666); /* get shm ID */
39 return (void *) shmid;
41 shptr = shmat(shmid,0,0); /* take the pointer to it */
43 perror("cannot attach shared memory");
46 memset((void *)shptr, fill, shm_size); /* second counter starts from "0" */
51 * Find a shared memory segment
52 * Input: an IPC key value
53 * the shared memory segment size
54 * Return: the address of the segment
56 void * ShmFind(key_t ipc_key, int shm_size)
59 int shmid; /* ID of the IPC shared memory segment */
60 if ( (shmid=shmget(ipc_key,shm_size,0))<0 ){ /* find shared memory ID */
61 perror("cannot find shared memory");
64 if ( (shptr=shmat(shmid,0,0)) < 0 ){ /* take the pointer to it */
65 perror("cannot attach shared memory");