change version.
[paraslash.git] / ipc.c
1 #include "para.h"
2 #include "error.h"
3 #include "ipc.h"
4 #include <sys/ipc.h>
5 #include <sys/shm.h>
6
7
8 int mutex_new(void)
9 {
10 int ret = semget(IPC_PRIVATE, 1, IPC_CREAT | 0666);
11 return ret < 0? -E_SEM_GET : ret;
12 }
13
14 int mutex_destroy(int id)
15 {
16 int ret = semctl(id, 0, IPC_RMID);
17 return ret < 0? -E_SEM_REMOVE : 1;
18 }
19
20 static void para_semop(int id, struct sembuf *sops, int num)
21 {
22 if (semop(id, sops, num) >= 0)
23 return;
24 PARA_WARNING_LOG("semop failed (%s), retrying\n", strerror(errno));
25 while (semop(id, sops, num) < 0)
26 ; /* nothing */
27 }
28
29 /**
30 * lock the given mutex
31 *
32 * \sa semop(2), struct misc_meta_data
33 */
34 void mutex_lock(int id)
35 {
36 struct sembuf sops[2] = {
37 {
38 .sem_num = 0,
39 .sem_op = 0,
40 .sem_flg = SEM_UNDO
41 },
42 {
43 .sem_num = 0,
44 .sem_op = 1,
45 .sem_flg = SEM_UNDO
46 }
47 };
48 para_semop(id, sops, 2);
49 }
50
51 /**
52 * unlock a mutex
53 *
54 * \sa semop(2), struct misc_meta_data
55 */
56 void mutex_unlock(int id)
57 {
58 struct sembuf sops[1] = {
59 {
60 .sem_num = 0,
61 .sem_op = -1,
62 .sem_flg = SEM_UNDO
63 },
64 };
65 para_semop(id, sops, 1);
66 }
67
68 /**
69 * create a new shared memory area of given size
70 *
71 * \sa shmget(2)
72 */
73 int shm_new(size_t size)
74 {
75 int ret = shmget(IPC_PRIVATE, size, IPC_CREAT | IPC_EXCL | 0600);
76 return ret < 0 ? -E_SHM_GET : ret;
77 }
78
79 /**
80 * destroy the given shared memory area
81 * \sa shmctl(2)
82 **/
83 int shm_destroy(int id)
84 {
85 struct shmid_ds shm_desc;
86 int ret = shmctl(id, IPC_RMID, &shm_desc);
87 return ret < 0? -E_SHM_DESTROY : ret;
88 }
89
90 /**
91 * attach a shared memory area
92 *
93 * \sa semop(2)
94 */
95 int shm_attach(int id, enum shm_attach_mode mode, void **result)
96 {
97 if (mode == ATTACH_RW) {
98 *result = shmat(id, NULL, 0);
99 return *result? 1 : -E_SHM_ATTACH;
100 }
101 *result = shmat(id, NULL, SHM_RDONLY);
102 return *result? 1 : -E_SHM_ATTACH;
103 }
104
105 int shm_detach(void *addr)
106 {
107 int ret = shmdt(addr);
108 return ret < 0? -E_SHM_DETACH : 1;
109 }