summaryrefslogtreecommitdiff
path: root/src/user/lib/esemaphore.c
diff options
context:
space:
mode:
authordzwdz2022-07-11 21:54:51 +0200
committerdzwdz2022-07-11 21:54:51 +0200
commit2e79a2e5af3affa7a6a3becdffb1c91d89af90af (patch)
treec253761c4ec010ad14b08f9ee8dfc1a50411b30f /src/user/lib/esemaphore.c
parent6c01d9a7e34e1fccc2775b0e2187ac5e50dd4392 (diff)
user: reorganize the userland sources
Diffstat (limited to 'src/user/lib/esemaphore.c')
-rw-r--r--src/user/lib/esemaphore.c55
1 files changed, 55 insertions, 0 deletions
diff --git a/src/user/lib/esemaphore.c b/src/user/lib/esemaphore.c
new file mode 100644
index 0000000..ed42ee9
--- /dev/null
+++ b/src/user/lib/esemaphore.c
@@ -0,0 +1,55 @@
+#include <user/lib/esemaphore.h>
+#include <user/lib/stdlib.h>
+#include <shared/flags.h>
+#include <shared/syscalls.h>
+
+void esem_signal(struct evil_sem *sem) {
+ _syscall_write(sem->signal, NULL, 0, 0);
+}
+
+void esem_wait(struct evil_sem *sem) {
+ _syscall_read(sem->wait, NULL, 0, 0);
+}
+
+struct evil_sem *esem_new(int value) {
+ handle_t ends_wait[2], ends_signal[2];
+ struct evil_sem *sem;
+
+ if (value < 0) return NULL;
+ if (_syscall_pipe(ends_wait, 0) < 0) return NULL;
+ if (_syscall_pipe(ends_signal, 0) < 0) goto fail_signal;
+ if (!(sem = malloc(sizeof *sem))) goto fail_malloc;
+
+ if (!_syscall_fork(FORK_NOREAP, NULL)) {
+ _syscall_close(ends_signal[1]);
+ while (_syscall_read(ends_signal[0], NULL, 0, 0) >= 0) {
+ if (!_syscall_fork(FORK_NOREAP, NULL)) {
+ _syscall_write(ends_wait[1], NULL, 0, 0);
+ _syscall_exit(0);
+ }
+ }
+ _syscall_exit(0);
+ }
+ _syscall_close(ends_signal[0]);
+ _syscall_close(ends_wait[1]);
+
+ sem->wait = ends_wait[0];
+ sem->signal = ends_signal[1];
+
+ while (value--) esem_signal(sem);
+ return sem;
+
+fail_malloc:
+ _syscall_close(ends_signal[0]);
+ _syscall_close(ends_signal[1]);
+fail_signal:
+ _syscall_close(ends_wait[0]);
+ _syscall_close(ends_wait[1]);
+ return NULL;
+}
+
+void esem_free(struct evil_sem *sem) {
+ _syscall_close(sem->wait);
+ _syscall_close(sem->signal);
+ free(sem);
+}