2715ca1e3d8855fb819bca6392e3ea58f36c2b49
[gapil.git] / sources / SharedMem.c
1 /***************************************************************
2  *
3  * File SharedMem.c 
4  * Routine for Shared Memory use
5  *
6  * Author: S. Piccardi
7  *
8  * $Id: SharedMem.c,v 1.1 2002/12/03 11:06:05 piccardi Exp $
9  *
10  ***************************************************************/
11 #include <sys/shm.h>                  /* SysV IPC shared memory declarations */
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <stdio.h>                                 /* standard I/O functions */
15 #include <fcntl.h>
16 #include <signal.h>                          /* signal handling declarations */
17 /*
18  * Function ShmCreate:
19  * Create and attach a SysV shared memory segment to the current process.
20  *
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
28  *
29  * Input:  an IPC key value
30  *         the shared memory segment size
31  * Return: the address of the segment
32  */
33 void * ShmCreate(key_t ipc_key, int shm_size, char fill) 
34 {
35     void * shptr;
36     int shmid;                        /* ID of the IPC shared memory segment */
37     shmid = shmget(ipc_key,shm_size,IPC_CREAT|0666);           /* get shm ID */
38     if (shmid < 0) { 
39         return (void *) shmid;
40     }
41     shptr = shmat(shmid,0,0);                      /* take the pointer to it */
42     if ( shptr == 0 ){    
43         perror("cannot attach shared memory");
44         exit(1);
45     }
46     memset((void *)shptr, fill, shm_size); /* second counter starts from "0" */
47     return shptr;
48 }
49 /*
50  * Function ShmFind:
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
55  */
56 void * ShmFind(key_t ipc_key, int shm_size) 
57 {
58     void * shptr;
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");
62         exit(1);
63     }
64     if ( (shptr=shmat(shmid,0,0)) < 0 ){    /* take the pointer to it */
65         perror("cannot attach shared memory");
66         exit(1);
67     }
68     return shptr;
69 }