xref: /PHP-5.5/sapi/fpm/fpm/fpm_shm.c (revision 65062b47)
1 
2 	/* $Id: fpm_shm.c,v 1.3 2008/05/24 17:38:47 anight Exp $ */
3 	/* (c) 2007,2008 Andrei Nigmatulin, Jerome Loyet */
4 
5 #include <sys/mman.h>
6 #include <errno.h>
7 #include <string.h>
8 
9 #include "fpm_shm.h"
10 #include "zlog.h"
11 
12 
13 /* MAP_ANON is deprecated, but not in macosx */
14 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
15 #define MAP_ANONYMOUS MAP_ANON
16 #endif
17 
18 static size_t fpm_shm_size = 0;
19 
fpm_shm_alloc(size_t size)20 void *fpm_shm_alloc(size_t size) /* {{{ */
21 {
22 	void *mem;
23 
24 	mem = mmap(0, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
25 
26 #ifdef MAP_FAILED
27 	if (mem == MAP_FAILED) {
28 		zlog(ZLOG_SYSERROR, "unable to allocate %zu bytes in shared memory: %s", size, strerror(errno));
29 		return NULL;
30 	}
31 #endif
32 
33 	if (!mem) {
34 		zlog(ZLOG_SYSERROR, "unable to allocate %zu bytes in shared memory", size);
35 		return NULL;
36 	}
37 
38 	memset(mem, 0, size);
39 	fpm_shm_size += size;
40 	return mem;
41 }
42 /* }}} */
43 
fpm_shm_free(void * mem,size_t size)44 int fpm_shm_free(void *mem, size_t size) /* {{{ */
45 {
46 	if (!mem) {
47 		zlog(ZLOG_ERROR, "mem is NULL");
48 		return 0;
49 	}
50 
51 	if (munmap(mem, size) == -1) {
52 		zlog(ZLOG_SYSERROR, "Unable to free shm");
53 		return 0;
54 	}
55 
56 	if (fpm_shm_size - size > 0) {
57 		fpm_shm_size -= size;
58 	} else {
59 		fpm_shm_size = 0;
60 	}
61 
62 	return 1;
63 }
64 /* }}} */
65 
fpm_shm_get_size_allocated()66 size_t fpm_shm_get_size_allocated() /* {{{*/
67 {
68 	return fpm_shm_size;
69 }
70 /* }}} */
71