2 * Copyright (C) 2006-2008 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file ipc.c Inter-process 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 The identifier 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 identifier.
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;