* Update Sendmail to version 8.12.10
[dragonfly.git] / contrib / sendmail / libsm / shm.c
1 /*
2  * Copyright (c) 2000-2001, 2003 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.2.6 2003/06/13 21:17:48 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 /*
21 **  SM_SHMSTART -- initialize shared memory segment.
22 **
23 **      Parameters:
24 **              key -- key for shared memory.
25 **              size -- size of segment.
26 **              shmflag -- initial flags.
27 **              shmid -- pointer to return id.
28 **              owner -- create segment.
29 **
30 **      Returns:
31 **              pointer to shared memory segment,
32 **              NULL on failure.
33 **
34 **      Side Effects:
35 **              attaches shared memory segment.
36 */
37
38 void *
39 sm_shmstart(key, size, shmflg, shmid, owner)
40         key_t key;
41         int size;
42         int shmflg;
43         int *shmid;
44         bool owner;
45 {
46         int save_errno;
47         void *shm = SM_SHM_NULL;
48
49         /* default: user/group accessible */
50         if (shmflg == 0)
51                 shmflg = SHM_R|SHM_W|(SHM_R>>3)|(SHM_W>>3);
52         if (owner)
53                 shmflg |= IPC_CREAT|IPC_EXCL;
54         *shmid = shmget(key, size, shmflg);
55         if (*shmid < 0)
56                 goto error;
57
58         shm = shmat(*shmid, (void *) 0, 0);
59         if (shm == SM_SHM_NULL)
60                 goto error;
61
62         return shm;
63
64   error:
65         save_errno = errno;
66         if (shm != SM_SHM_NULL || *shmid >= 0)
67                 sm_shmstop(shm, *shmid, owner);
68         *shmid = SM_SHM_NO_ID;
69         errno = save_errno;
70         return (void *) 0;
71 }
72
73
74 /*
75 **  SM_SHMSTOP -- stop using shared memory segment.
76 **
77 **      Parameters:
78 **              shm -- pointer to shared memory.
79 **              shmid -- id.
80 **              owner -- delete segment.
81 **
82 **      Returns:
83 **              0 on success.
84 **              < 0 on failure.
85 **
86 **      Side Effects:
87 **              detaches (and maybe removes) shared memory segment.
88 */
89
90
91 int
92 sm_shmstop(shm, shmid, owner)
93         void *shm;
94         int shmid;
95         bool owner;
96 {
97         int r;
98
99         if (shm != SM_SHM_NULL && (r = shmdt(shm)) < 0)
100                 return r;
101         if (owner && shmid >= 0 && (r = shmctl(shmid, IPC_RMID, NULL)) < 0)
102                 return r;
103         return 0;
104 }
105
106
107 #endif /* SM_CONF_SHM */