From 42c7c3c1e6a7b6b001e7ae4f9083b29a5fb872e8 Mon Sep 17 00:00:00 2001 From: Alex Kotov Date: Tue, 15 Dec 2020 20:41:00 +0500 Subject: [PATCH] Use semaphores --- configure.ac | 4 ++++ tests/test_fork.c | 43 +++++++++++++++++++++++++++++++++++++++---- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/configure.ac b/configure.ac index 2e75261..7087919 100644 --- a/configure.ac +++ b/configure.ac @@ -39,6 +39,7 @@ AC_CHECK_HEADERS([sys/mman.h]) AC_CHECK_HEADERS([sys/stat.h]) AC_CHECK_HEADERS([sys/types.h]) AC_CHECK_HEADERS([sys/wait.h]) +AC_CHECK_HEADERS([time.h]) AC_CHECK_HEADERS([unistd.h]) AC_CHECK_FUNCS([close]) @@ -53,7 +54,10 @@ AC_CHECK_FUNCS([strcpy]) AC_CHECK_FUNCS([strlen]) AC_CHECK_FUNCS([waitpid]) +AC_SEARCH_LIBS([sem_getvalue], [pthread]) AC_SEARCH_LIBS([sem_init], [pthread]) +AC_SEARCH_LIBS([sem_post], [pthread]) +AC_SEARCH_LIBS([sem_timedwait], [pthread]) AC_SEARCH_LIBS([shm_open], [rt]) AC_SEARCH_LIBS([shm_unlink], [rt]) diff --git a/tests/test_fork.c b/tests/test_fork.c index 0d06d3e..7caea01 100644 --- a/tests/test_fork.c +++ b/tests/test_fork.c @@ -1,3 +1,5 @@ +#define _POSIX_C_SOURCE 200809L + #include #include @@ -6,6 +8,7 @@ #include #include #include +#include #include static const char name[] = "/foobar"; @@ -34,7 +37,13 @@ int main() const ShmemqFrame frame = shmemq_pop_start(consumer); if (frame == NULL) { - sleep(1); + struct timespec tspec; + const int clock_result = clock_gettime(CLOCK_REALTIME, &tspec); + assert(clock_result == 0); + + tspec.tv_nsec += 1000; + + sem_timedwait(&consumer->buffer->header.read_sem, &tspec); continue; } @@ -53,14 +62,23 @@ int main() shmemq_pop_end(consumer, &error); assert(error == SHMEMQ_ERROR_NONE); + + int sem_value; + const int sem_getvalue_result = + sem_getvalue(&consumer->buffer->header.write_sem, &sem_value); + assert(sem_getvalue_result == 0); + + if (sem_value == 0) { + const int sem_post_result = + sem_post(&consumer->buffer->header.write_sem); + assert(sem_post_result == 0); + } } } else { atexit(on_exit); signal(SIGABRT, on_signal); - sleep(1); - producer = shmemq_new(name, false, &error); assert(error == SHMEMQ_ERROR_NONE); @@ -68,7 +86,13 @@ int main() const ShmemqFrame frame = shmemq_push_start(producer); if (frame == NULL) { - sleep(1); + struct timespec tspec; + const int clock_result = clock_gettime(CLOCK_REALTIME, &tspec); + assert(clock_result == 0); + + tspec.tv_nsec += 1000; + + sem_timedwait(&producer->buffer->header.write_sem, &tspec); continue; } @@ -84,6 +108,17 @@ int main() shmemq_push_end(producer, sizeof(unsigned), &error); assert(error == SHMEMQ_ERROR_NONE); + + int sem_value; + const int sem_getvalue_result = + sem_getvalue(&producer->buffer->header.read_sem, &sem_value); + assert(sem_getvalue_result == 0); + + if (sem_value == 0) { + const int sem_post_result = + sem_post(&producer->buffer->header.read_sem); + assert(sem_post_result == 0); + } } }