From 6b191f8c631c0455c4fc9fbb8b0f9e83bb3aa748 Mon Sep 17 00:00:00 2001 From: Wildan M Date: Wed, 7 Jan 2026 01:44:51 +0700 Subject: [PATCH] Adjust mutex test --- tests/stdio/mutex.c | 59 +++++++++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 21 deletions(-) diff --git a/tests/stdio/mutex.c b/tests/stdio/mutex.c index 3d9be9d8db..dc729d3c5f 100644 --- a/tests/stdio/mutex.c +++ b/tests/stdio/mutex.c @@ -1,30 +1,47 @@ #include #include +#include #include "test_helpers.h" -int main(void) { - FILE *f = fopen("stdio/stdio.in", "r"); - ERROR_IF(fopen, f, == NULL); +FILE *f; - flockfile(f); +void* thread_wontlock(void* arg) { + (void)arg; - // Commenting this out should cause a deadlock: - // flockfile(f); + int result = ftrylockfile(f); + UNEXP_IF(ftrylockfile, result, == 0); - if (!ftrylockfile(f)) { - puts("Mutex unlocked but it shouldn't be"); - exit(EXIT_FAILURE); - } - funlockfile(f); - - if (ftrylockfile(f)) { - puts("Mutex locked but it shouldn't be"); - exit(EXIT_FAILURE); - } - if (!ftrylockfile(f)) { - puts("Mutex unlocked but it shouldn't be"); - exit(EXIT_FAILURE); - } - funlockfile(f); + return NULL; +} + +void* thread_willlock(void* arg) { + (void)arg; + + int result = ftrylockfile(f); + UNEXP_IF(ftrylockfile, result, != 0); + + return NULL; +} + +int main(void) { + f = fopen("stdio/stdio.in", "r"); + ERROR_IF(fopen, f, == NULL); + flockfile(f); + flockfile(f); + thread_willlock(NULL); + + pthread_t thread; + for (int i = 1; i <= 3; i++) { + pthread_create(&thread, NULL, thread_wontlock, NULL); + pthread_join(thread, NULL); + funlockfile(f); + } + + pthread_create(&thread, NULL, thread_willlock, NULL); + pthread_join(thread, NULL); + + // TODO: glibc refuses to quit test without this + // but in relibc, it will result in EPERM + // funlockfile(f); }