summaryrefslogtreecommitdiff
path: root/src/libc/esemaphore.c
diff options
context:
space:
mode:
authordzwdz2023-08-14 18:51:07 +0200
committerdzwdz2023-08-14 18:51:07 +0200
commit642b5fb0007b64c77d186fcb018d571152ee1d47 (patch)
tree1c466461f3602d306be309a053edae558ef2568e /src/libc/esemaphore.c
parent8050069c57b729c18c19b1a03ab6e4bf63b4735e (diff)
reorganization: first steps
Diffstat (limited to 'src/libc/esemaphore.c')
-rw-r--r--src/libc/esemaphore.c56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/libc/esemaphore.c b/src/libc/esemaphore.c
new file mode 100644
index 0000000..2707d11
--- /dev/null
+++ b/src/libc/esemaphore.c
@@ -0,0 +1,56 @@
+#include <camellia/flags.h>
+#include <camellia/syscalls.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <esemaphore.h>
+
+void esem_signal(struct evil_sem *sem) {
+ _sys_write(sem->signal, NULL, 0, 0, 0);
+}
+
+void esem_wait(struct evil_sem *sem) {
+ _sys_read(sem->wait, NULL, 0, 0);
+}
+
+struct evil_sem *esem_new(int value) {
+ hid_t ends_wait[2], ends_signal[2];
+ struct evil_sem *sem;
+
+ if (value < 0) return NULL;
+ if (_sys_pipe(ends_wait, 0) < 0) return NULL;
+ if (_sys_pipe(ends_signal, 0) < 0) goto fail_signal;
+ if (!(sem = malloc(sizeof *sem))) goto fail_malloc;
+
+ if (!_sys_fork(FORK_NOREAP, NULL)) {
+ close(ends_signal[1]);
+ while (_sys_read(ends_signal[0], NULL, 0, 0) >= 0) {
+ if (!_sys_fork(FORK_NOREAP, NULL)) {
+ _sys_write(ends_wait[1], NULL, 0, 0, 0);
+ exit(0);
+ }
+ }
+ exit(0);
+ }
+ close(ends_signal[0]);
+ close(ends_wait[1]);
+
+ sem->wait = ends_wait[0];
+ sem->signal = ends_signal[1];
+
+ while (value--) esem_signal(sem);
+ return sem;
+
+fail_malloc:
+ close(ends_signal[0]);
+ close(ends_signal[1]);
+fail_signal:
+ close(ends_wait[0]);
+ close(ends_wait[1]);
+ return NULL;
+}
+
+void esem_free(struct evil_sem *sem) {
+ close(sem->wait);
+ close(sem->signal);
+ free(sem);
+}