3 * Copyright (C) 2002 Simone Piccardi
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or (at
8 * your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 /***************************************************************
22 * Routine for Shared Memory use
26 * $Id: SharedMem.c,v 1.2 2002/12/03 22:30:11 piccardi Exp $
28 ***************************************************************/
29 #include <sys/shm.h> /* SysV IPC shared memory declarations */
30 #include <sys/types.h>
32 #include <stdio.h> /* standard I/O functions */
34 #include <signal.h> /* signal handling declarations */
37 * Create and attach a SysV shared memory segment to the current process.
39 * First call get a shared memory segment with KEY key access and size SIZE,
40 * by creating it with R/W privilege for the user (this is the meaning of
41 * the ored flags). The function return an identifier shmid used for any
42 * further reference to the shared memory segment.
43 * Second call attach the shared memory segment to this process and return a
44 * pointer to it (of void * type).
45 * Then initialize shared memory to the given value
47 * Input: an IPC key value
48 * the shared memory segment size
49 * Return: the address of the segment
51 void * ShmCreate(key_t ipc_key, int shm_size, char fill)
54 int shmid; /* ID of the IPC shared memory segment */
55 shmid = shmget(ipc_key,shm_size,IPC_CREAT|0666); /* get shm ID */
57 return (void *) shmid;
59 shptr = shmat(shmid,0,0); /* take the pointer to it */
61 perror("cannot attach shared memory");
64 memset((void *)shptr, fill, shm_size); /* second counter starts from "0" */
69 * Find a shared memory segment
70 * Input: an IPC key value
71 * the shared memory segment size
72 * Return: the address of the segment
74 void * ShmFind(key_t ipc_key, int shm_size)
77 int shmid; /* ID of the IPC shared memory segment */
78 if ( (shmid=shmget(ipc_key,shm_size,0))<0 ){ /* find shared memory ID */
79 perror("cannot find shared memory");
82 if ( (shptr=shmat(shmid,0,0)) < 0 ){ /* take the pointer to it */
83 perror("cannot attach shared memory");