1
|
1 /*
|
|
2 * shmem.c - Shared memory allocation
|
|
3 *
|
|
4 * based on mpg123's xfermem.c by
|
|
5 * Oliver Fromme <oliver.fromme@heim3.tu-clausthal.de>
|
|
6 * Sun Apr 6 02:26:26 MET DST 1997
|
|
7 */
|
|
8
|
|
9 #include <stdio.h>
|
|
10 #include <stdlib.h>
|
|
11 #include <string.h>
|
|
12 #include <unistd.h>
|
|
13 #include <errno.h>
|
|
14 #include <sys/types.h>
|
|
15 #include <sys/time.h>
|
|
16 #include <sys/uio.h>
|
|
17 #include <sys/mman.h>
|
|
18 #include <sys/socket.h>
|
|
19 #include <fcntl.h>
|
|
20
|
|
21 #ifdef AIX
|
|
22 #include <sys/select.h>
|
|
23 #endif
|
|
24
|
|
25 #include <sys/ipc.h>
|
|
26 #include <sys/shm.h>
|
|
27
|
|
28 extern int errno;
|
|
29
|
|
30 #if defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
|
|
31 #define MAP_ANON MAP_ANONYMOUS
|
|
32 #endif
|
|
33
|
|
34 static int shmem_type=0;
|
|
35
|
|
36 void* shmem_alloc(int size){
|
|
37 void* p;
|
|
38 int devzero;
|
|
39 while(1){
|
|
40 switch(shmem_type){
|
|
41 case 0: // ========= MAP_ANON|MAP_SHARED ==========
|
|
42 p=mmap(0,size,PROT_READ|PROT_WRITE,MAP_ANON|MAP_SHARED,-1,0);
|
|
43 if(p==MAP_FAILED) break; // failed
|
|
44 printf("shmem: %d bytes allocated using mmap anon (%X)\n",size,p);
|
|
45 return p;
|
|
46 case 1: // ========= MAP_SHARED + /dev/zero ==========
|
|
47 if ((devzero = open("/dev/zero", O_RDWR, 0)) == -1) break;
|
|
48 p=mmap(0,size,PROT_READ|PROT_WRITE,MAP_SHARED,devzero,0);
|
|
49 if(p==MAP_FAILED) break; // failed
|
|
50 printf("shmem: %d bytes allocated using mmap /dev/zero (%X)\n",size,p);
|
|
51 return p;
|
|
52 case 2: { // ========= shmget() ==========
|
|
53 struct shmid_ds shmemds;
|
|
54 int shmemid;
|
|
55 if ((shmemid = shmget(IPC_PRIVATE, size, IPC_CREAT | 0600)) == -1) break;
|
|
56 if ((int)(p = shmat(shmemid, 0, 0)) == -1){
|
|
57 perror ("shmat()");
|
|
58 shmctl (shmemid, IPC_RMID, &shmemds);
|
|
59 break;
|
|
60 }
|
|
61 if (shmctl(shmemid, IPC_RMID, &shmemds) == -1) {
|
|
62 perror ("shmctl()");
|
|
63 if (shmdt(p) == -1) perror ("shmdt()");
|
|
64 break;
|
|
65 }
|
|
66 printf("shmem: %d bytes allocated using shmget() & shmat() (%X)\n",size,p);
|
|
67 return p;
|
|
68 }
|
|
69 default:
|
|
70 printf("FATAL: Cannot alloate %d bytes shared memory :(\n",size);
|
|
71 return NULL;
|
|
72 }
|
|
73 ++shmem_type;
|
|
74 }
|
|
75 }
|
|
76
|
|
77 void shmem_free(void* p){
|
|
78 switch(shmem_type){
|
|
79 case 2:
|
|
80 if (shmdt(p) == -1) perror ("shmdt()");
|
|
81 break;
|
|
82 }
|
|
83 }
|