From: Scott Worley Date: Wed, 13 Sep 2023 21:51:07 +0000 (-0700) Subject: test: Try writing to flock-locked files X-Git-Tag: v1.0.0~4 X-Git-Url: http://git.scottworley.com/tl-append/commitdiff_plain/a1160bb5b12b273f44860ccd4f028cb22c4f5e4d?ds=sidebyside test: Try writing to flock-locked files --- diff --git a/tl-append-test.c b/tl-append-test.c index 20ae7fb..04c679e 100644 --- a/tl-append-test.c +++ b/tl-append-test.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -195,19 +196,23 @@ static void test_encode_time() { assert(encoded[19] == '\0'); } -static FILE *take_lock() { - FILE *f = fopen(FILENAME, "a"); - if (f == NULL) - die_err("Couldn't open file for locking"); +static FILE *take_lock(FILE *f, char *lock_type) { int fd = fileno(f); if (fd == -1) die_err("Couldn't get file descriptor for locking"); - if (fcntl(fd, F_SETLK, - &(struct flock){.l_type = F_WRLCK, - .l_whence = SEEK_SET, - .l_start = 0, - .l_len = 0}) == -1) - die_err("Couldn't take lock"); + if (strcmp(lock_type, "fcntl") == 0) { + if (fcntl(fd, F_SETLK, + &(struct flock){.l_type = F_WRLCK, + .l_whence = SEEK_SET, + .l_start = 0, + .l_len = 0}) == -1) + die_err("Couldn't take fcntl lock"); + } else if (strcmp(lock_type, "flock") == 0) { + if (flock(fd, LOCK_EX) == -1) + die_err("Couldn't take flock lock"); + } else { + die("Bad lock type"); + } return f; } @@ -217,7 +222,7 @@ static void release_lock(FILE *f) { } static void *release_lock_after_delay(void *f) { - sleep(2); + sleep(1); release_lock((FILE *)f); return NULL; } @@ -247,13 +252,17 @@ static void write_and_read_two_lines() { verify_log_contents((ex_t[]){e1, e2, END}); } -static void write_to_locked_log() { +static void write_to_locked_log(char *lock_types[]) { remove_logfile(); ex_t e1 = write_to_tl_append("begin\n"); - FILE *lock = take_lock(); + FILE *f = fopen(FILENAME, "a"); + if (f == NULL) + die_err("Couldn't open file for locking"); + for (int i = 0; lock_types[i]; i++) + take_lock(f, lock_types[0]); pthread_t unlock_thread; int create_ret = - pthread_create(&unlock_thread, NULL, &release_lock_after_delay, lock); + pthread_create(&unlock_thread, NULL, &release_lock_after_delay, f); if (create_ret != 0) { errno = create_ret; die_err("Couldn't start thread"); @@ -301,6 +310,10 @@ int main() { test_encode_time(); write_and_read_line(); write_and_read_two_lines(); - write_to_locked_log(); + write_to_locked_log((char *[]){NULL}); + write_to_locked_log((char *[]){"fcntl", NULL}); + write_to_locked_log((char *[]){"flock", NULL}); + write_to_locked_log((char *[]){"flock", "fcntl", NULL}); + write_to_locked_log((char *[]){"fcntl", "flock", NULL}); write_concurrently(); }