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