2 * Copyright (C) 2006-2007 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file ipc.c interprocess communication and shared memory helpers */
19 * \return the identifier for the new mutex on success, \a -E_SEM_GET
26 int ret = semget(IPC_PRIVATE, 1, IPC_CREAT | 0666);
27 return ret < 0? -E_SEM_GET : ret;
33 * \param id the identifier of the mutex to be destroyed
35 * \return Positive on success, \a -E_SEM_REMOVE on errors.
39 int mutex_destroy(int id)
41 int ret = semctl(id, 0, IPC_RMID);
42 return ret < 0? -E_SEM_REMOVE : 1;
45 static void para_semop(int id, struct sembuf *sops, int num)
48 if (semop(id, sops, num) >= 0)
50 } while (errno == EINTR);
52 PARA_NOTICE_LOG("semaphore set %d was removed\n", id);
55 PARA_EMERG_LOG("fatal semop error %s: pid %d\n", strerror(errno),
61 * lock the given mutex
63 * \param id of the shared memory area to lock
65 * This function either succeeds or aborts.
67 * \sa semop(2), struct misc_meta_data
69 void mutex_lock(int id)
71 struct sembuf sops[2] = {
83 para_semop(id, sops, 2);
89 * \param id the identifier of the mutex
91 * This function either succeeds or aborts.
93 * \sa semop(2), struct misc_meta_data
95 void mutex_unlock(int id)
97 struct sembuf sops[1] = {
104 para_semop(id, sops, 1);
108 * create a new shared memory area of given size
110 * \param size the size of the shared memory area to create
112 * \return The id of the shared memory areay on success, \a -E_SHM_GET on errors.
116 int shm_new(size_t size)
118 int ret = shmget(IPC_PRIVATE, size, IPC_CREAT | IPC_EXCL | 0600);
119 return ret < 0 ? -E_SHM_GET : ret;
123 * destroy the given shared memory area
125 * \param id the shared memory id
127 * \return The return value of the underlying shmctl() call on success,
128 * \a -E_SHM_DESTROY on errors.
132 int shm_destroy(int id)
134 struct shmid_ds shm_desc;
135 int ret = shmctl(id, IPC_RMID, &shm_desc);
136 return ret < 0? -E_SHM_DESTROY : ret;
140 * attach a shared memory segment
142 * \param id the identifier of the shared memory segment to attach
143 * \param mode either ATTACH_RO (read only) or ATTACH_RW (read/write)
144 * \param result points to the attached area just attached
146 * \return positive on success, \a -E_SHM_ATTACH on errors.
150 int shm_attach(int id, enum shm_attach_mode mode, void **result)
152 if (mode == ATTACH_RW) {
153 *result = shmat(id, NULL, 0);
154 return *result? 1 : -E_SHM_ATTACH;
156 *result = shmat(id, NULL, SHM_RDONLY);
157 return *result? 1 : -E_SHM_ATTACH;
161 * detach a shared memory segment
163 * \param addr the address of the attached segment
165 * \return positive on success, \a -E_SHM_DETACH on errors.
169 int shm_detach(void *addr)
171 int ret = shmdt(addr);
172 return ret < 0? -E_SHM_DETACH : 1;