2 * shmem.c - Shared memory allocation
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
16 #include <sys/types.h>
19 #ifdef HAVE_SYS_MMAN_H
21 #elif defined(__BEOS__)
24 #include <sys/socket.h>
30 #include <sys/select.h>
38 #if defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
39 #define MAP_ANON MAP_ANONYMOUS
42 static int shmem_type
=0;
44 void* shmem_alloc(int size
){
46 static int devzero
= -1;
49 case 0: // ========= MAP_ANON|MAP_SHARED ==========
51 p
=mmap(0,size
,PROT_READ
|PROT_WRITE
,MAP_ANON
|MAP_SHARED
,-1,0);
52 if(p
==MAP_FAILED
) break; // failed
53 mp_dbg(MSGT_OSDEP
, MSGL_DBG2
, "shmem: %d bytes allocated using mmap anon (%p)\n",size
,p
);
56 // system does not support MAP_ANON at all (e.g. solaris 2.5.1/2.6), just fail
57 mp_dbg(MSGT_OSDEP
, MSGL_DBG3
, "shmem: using mmap anon failed\n");
60 case 1: // ========= MAP_SHARED + /dev/zero ==========
61 if (devzero
== -1 && (devzero
= open("/dev/zero", O_RDWR
, 0)) == -1) break;
62 p
=mmap(0,size
,PROT_READ
|PROT_WRITE
,MAP_SHARED
,devzero
,0);
63 if(p
==MAP_FAILED
) break; // failed
64 mp_dbg(MSGT_OSDEP
, MSGL_DBG2
, "shmem: %d bytes allocated using mmap /dev/zero (%p)\n",size
,p
);
66 case 2: { // ========= shmget() ==========
68 struct shmid_ds shmemds
;
70 if ((shmemid
= shmget(IPC_PRIVATE
, size
, IPC_CREAT
| 0600)) == -1) break;
71 if ((p
= shmat(shmemid
, 0, 0)) == (void *)-1){
72 mp_msg(MSGT_OSDEP
, MSGL_ERR
, "shmem: shmat() failed: %s\n", strerror(errno
));
73 shmctl (shmemid
, IPC_RMID
, &shmemds
);
76 if (shmctl(shmemid
, IPC_RMID
, &shmemds
) == -1) {
77 mp_msg(MSGT_OSDEP
, MSGL_ERR
, "shmem: shmctl() failed: %s\n", strerror(errno
));
78 if (shmdt(p
) == -1) perror ("shmdt()");
81 mp_dbg(MSGT_OSDEP
, MSGL_DBG2
, "shmem: %d bytes allocated using SHM (%p)\n",size
,p
);
84 mp_msg(MSGT_OSDEP
, MSGL_FATAL
, "shmem: no SHM support was compiled in!\n");
89 mp_msg(MSGT_OSDEP
, MSGL_FATAL
,
90 "FATAL: Cannot allocate %d bytes of shared memory :(\n",size
);
97 void shmem_free(void* p
,int size
){
102 mp_msg(MSGT_OSDEP
, MSGL_ERR
, "munmap failed on %p %d bytes: %s\n",
103 p
,size
,strerror(errno
));
109 mp_msg(MSGT_OSDEP
, MSGL_ERR
, "shmfree: shmdt() failed: %s\n",
112 mp_msg(MSGT_OSDEP
, MSGL_ERR
, "shmfree: no SHM support was compiled in!\n");