Aggiornamento note copyright
[gapil.git] / listati / SharedMem.c
1 /* Function ShmCreate  Create a SysV shared memory segment */
2 void * ShmCreate(key_t ipc_key, int shm_size, int perm, int fill) 
3 {
4     void * shm_ptr;
5     int shm_id;     /* ID of the IPC shared memory segment */
6     shm_id = shmget(ipc_key, shm_size, IPC_CREAT|perm); /* get shm ID */
7     if (shm_id < 0) { 
8         return NULL;
9     }
10     shm_ptr = shmat(shm_id, NULL, 0);         /* map it into memory */
11     if (shm_ptr < 0) {
12         return NULL;
13     }
14     memset((void *)shm_ptr, fill, shm_size);  /* fill segment */
15     return shm_ptr;
16 }
17 /* Function ShmFind: Find a SysV shared memory segment  */
18 void * ShmFind(key_t ipc_key, int shm_size) 
19 {
20     void * shm_ptr;
21     int shm_id;     /* ID of the SysV shared memory segment */
22     shm_id = shmget(ipc_key, shm_size, 0);    /* find shared memory ID */
23     if (shm_id < 0) {
24         return NULL;
25     }
26     shm_ptr = shmat(shm_id, NULL, 0);         /* map it into memory */
27     if (shm_ptr < 0) {
28         return NULL;
29     }
30     return shm_ptr;
31 }
32 /* Function ShmRemove: Schedule removal for a SysV shared memory segment  */
33 int ShmRemove(key_t ipc_key, void * shm_ptr) 
34 {
35     int shm_id;     /* ID of the SysV shared memory segment */
36     /* first detach segment */
37     if (shmdt(shm_ptr) < 0) {
38         return -1;
39     }
40     /* schedule segment removal */
41     shm_id = shmget(ipc_key, 0, 0);           /* find shared memory ID */
42     if (shm_id < 0) {
43         if (errno == EIDRM) return 0;
44         return -1;
45     }
46     if (shmctl(shm_id, IPC_RMID, NULL) < 0) { /* ask for removal */
47         if (errno == EIDRM) return 0;
48         return -1;
49     }
50     return 0;
51 }