2 * Copyright (C) 2006-2009 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 negative error code
26 int ret
= semget(IPC_PRIVATE
, 1, IPC_CREAT
| 0666);
27 return ret
< 0? -ERRNO_TO_PARA_ERROR(errno
) : ret
;
33 * \param id The identifier of the mutex to be destroyed.
39 int mutex_destroy(int id
)
41 int ret
= semctl(id
, 0, IPC_RMID
);
42 return ret
< 0? -ERRNO_TO_PARA_ERROR(errno
) : 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_CRIT_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 array on success, a negative error
117 int shm_new(size_t size
)
119 int ret
= shmget(IPC_PRIVATE
, size
, IPC_CREAT
| IPC_EXCL
| 0600);
120 return ret
< 0 ? -ERRNO_TO_PARA_ERROR(errno
) : ret
;
124 * Destroy the given shared memory area.
126 * \param id The shared memory identifier.
128 * \return The return value of the underlying shmctl() call on success,
129 * a negative error code on errors.
133 int shm_destroy(int id
)
135 struct shmid_ds shm_desc
;
136 int ret
= shmctl(id
, IPC_RMID
, &shm_desc
);
137 return ret
< 0? -ERRNO_TO_PARA_ERROR(errno
) : ret
;
141 * Attach a shared memory segment.
143 * \param id The identifier of the shared memory segment to attach.
144 * \param mode Either ATTACH_RO (read only) or ATTACH_RW (read/write).
145 * \param result Points to the attached area just attached on success.
151 int shm_attach(int id
, enum shm_attach_mode mode
, void **result
)
153 if (mode
== ATTACH_RW
)
154 *result
= shmat(id
, NULL
, 0);
156 *result
= shmat(id
, NULL
, SHM_RDONLY
);
157 return *result
== (void *) -1? -ERRNO_TO_PARA_ERROR(errno
) : 1;
161 * Detach a shared memory segment.
163 * \param addr The address of the attached segment.
169 int shm_detach(void *addr
)
171 int ret
= shmdt(addr
);
172 return ret
< 0? -ERRNO_TO_PARA_ERROR(errno
) : 1;