3 * Copyright (C) Igor Sysoev
4 * Copyright (C) Nginx, Inc.
8 #include <ngx_config.h>
12 #if (NGX_HAVE_MAP_ANON)
15 ngx_shm_alloc(ngx_shm_t *shm)
17 shm->addr = (u_char *) mmap(NULL, shm->size,
19 MAP_ANON|MAP_SHARED, -1, 0);
21 if (shm->addr == MAP_FAILED) {
22 ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno,
23 "mmap(MAP_ANON|MAP_SHARED, %uz) failed", shm->size);
32 ngx_shm_free(ngx_shm_t *shm)
34 if (munmap((void *) shm->addr, shm->size) == -1) {
35 ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno,
36 "munmap(%p, %uz) failed", shm->addr, shm->size);
40 #elif (NGX_HAVE_MAP_DEVZERO)
43 ngx_shm_alloc(ngx_shm_t *shm)
47 fd = open("/dev/zero", O_RDWR);
50 ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno,
51 "open(\"/dev/zero\") failed");
55 shm->addr = (u_char *) mmap(NULL, shm->size, PROT_READ|PROT_WRITE,
58 if (shm->addr == MAP_FAILED) {
59 ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno,
60 "mmap(/dev/zero, MAP_SHARED, %uz) failed", shm->size);
63 if (close(fd) == -1) {
64 ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno,
65 "close(\"/dev/zero\") failed");
68 return (shm->addr == MAP_FAILED) ? NGX_ERROR : NGX_OK;
73 ngx_shm_free(ngx_shm_t *shm)
75 if (munmap((void *) shm->addr, shm->size) == -1) {
76 ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno,
77 "munmap(%p, %uz) failed", shm->addr, shm->size);
81 #elif (NGX_HAVE_SYSVSHM)
88 ngx_shm_alloc(ngx_shm_t *shm)
92 id = shmget(IPC_PRIVATE, shm->size, (SHM_R|SHM_W|IPC_CREAT));
95 ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno,
96 "shmget(%uz) failed", shm->size);
100 ngx_log_debug1(NGX_LOG_DEBUG_CORE, shm->log, 0, "shmget id: %d", id);
102 shm->addr = shmat(id, NULL, 0);
104 if (shm->addr == (void *) -1) {
105 ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno, "shmat() failed");
108 if (shmctl(id, IPC_RMID, NULL) == -1) {
109 ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno,
110 "shmctl(IPC_RMID) failed");
113 return (shm->addr == (void *) -1) ? NGX_ERROR : NGX_OK;
118 ngx_shm_free(ngx_shm_t *shm)
120 if (shmdt(shm->addr) == -1) {
121 ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno,
122 "shmdt(%p) failed", shm->addr);