1 /* 2 * Copyright (c) 2000-2001 Sendmail, Inc. and its suppliers. 3 * All rights reserved. 4 * 5 * By using this file, you agree to the terms and conditions set 6 * forth in the LICENSE file which can be found at the top level of 7 * the sendmail distribution. 8 */ 9 10 #include <sm/gen.h> 11 SM_RCSID("@(#)$Id: shm.c,v 1.10 2001/12/14 00:22:58 ca Exp $") 12 13 #if SM_CONF_SHM 14 # include <stdlib.h> 15 # include <unistd.h> 16 # include <errno.h> 17 # include <sm/shm.h> 18 19 /* 20 ** SM_SHMSTART -- initialize shared memory segment. 21 ** 22 ** Parameters: 23 ** key -- key for shared memory. 24 ** size -- size of segment. 25 ** shmflag -- initial flags. 26 ** shmid -- pointer to return id. 27 ** owner -- create segment. 28 ** 29 ** Returns: 30 ** pointer to shared memory segment, 31 ** NULL on failure. 32 ** 33 ** Side Effects: 34 ** attaches shared memory segment. 35 */ 36 37 void * 38 sm_shmstart(key, size, shmflg, shmid, owner) 39 key_t key; 40 int size; 41 int shmflg; 42 int *shmid; 43 bool owner; 44 { 45 int save_errno; 46 void *shm = SM_SHM_NULL; 47 48 /* default: user/group accessible */ 49 if (shmflg == 0) 50 shmflg = SHM_R|SHM_W|(SHM_R>>3)|(SHM_W>>3); 51 if (owner) 52 shmflg |= IPC_CREAT|IPC_EXCL; 53 *shmid = shmget(key, size, shmflg); 54 if (*shmid < 0) 55 goto error; 56 57 shm = shmat(*shmid, (void *) 0, 0); 58 if (shm == SM_SHM_NULL) 59 goto error; 60 61 return shm; 62 63 error: 64 save_errno = errno; 65 if (shm != SM_SHM_NULL || *shmid >= 0) 66 sm_shmstop(shm, *shmid, owner); 67 *shmid = SM_SHM_NO_ID; 68 errno = save_errno; 69 return (void *) 0; 70 } 71 72 /* 73 ** SM_SHMSTOP -- stop using shared memory segment. 74 ** 75 ** Parameters: 76 ** shm -- pointer to shared memory. 77 ** shmid -- id. 78 ** owner -- delete segment. 79 ** 80 ** Returns: 81 ** 0 on success. 82 ** < 0 on failure. 83 ** 84 ** Side Effects: 85 ** detaches (and maybe removes) shared memory segment. 86 */ 87 88 int 89 sm_shmstop(shm, shmid, owner) 90 void *shm; 91 int shmid; 92 bool owner; 93 { 94 int r; 95 96 if (shm != SM_SHM_NULL && (r = shmdt(shm)) < 0) 97 return r; 98 if (owner && shmid >= 0 && (r = shmctl(shmid, IPC_RMID, NULL)) < 0) 99 return r; 100 return 0; 101 } 102 #endif /* SM_CONF_SHM */ 103