From 72778681704b3d41b4ffb7a9051c5eff4d4bc520 Mon Sep 17 00:00:00 2001 From: Alain Zscheile Date: Wed, 4 Jan 2023 08:52:23 +0100 Subject: [PATCH] use flock to provide basic concurrency protection --- bin/main.c | 49 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/bin/main.c b/bin/main.c index 907ff84..ee92c02 100644 --- a/bin/main.c +++ b/bin/main.c @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -101,12 +102,6 @@ int main(int argc, const char *argv[]) return -1; } - fd = open(dbfile, O_RDWR | O_CREAT | O_NOCTTY); - if(fd == -1) { - perror("y16t: unable to open file"); - return -1; - } - if(-1 == y16t_parse_coordinate(argv[3], x, sizeof(x))) { fprintf(stderr, "y16t: invalid coordinate X\n"); return -1; @@ -120,6 +115,17 @@ int main(int argc, const char *argv[]) return -1; } + fd = open(dbfile, O_RDWR | O_CREAT | O_NOCTTY); + if(fd == -1) { + perror("y16t: unable to open file"); + return -1; + } + + if(flock(fd, LOCK_EX) == -1) { + perror("y16t: unable to lock file"); + return -1; + } + tmp = y16t_db_insert(fd, x, y, z); if(tmp < 0) { fprintf(stderr, "y16t: insert failed with %s\n", strerror(-tmp)); @@ -133,12 +139,6 @@ int main(int argc, const char *argv[]) return -1; } - fd = open(dbfile, O_RDWR | O_NOCTTY); - if(fd == -1) { - perror("y16t: unable to open file"); - return -1; - } - if(-1 == y16t_parse_coordinate(argv[3], x, sizeof(x))) { fprintf(stderr, "y16t: invalid coordinate X\n"); return -1; @@ -152,6 +152,17 @@ int main(int argc, const char *argv[]) return -1; } + fd = open(dbfile, O_RDWR | O_NOCTTY); + if(fd == -1) { + perror("y16t: unable to open file"); + return -1; + } + + if(flock(fd, LOCK_EX) == -1) { + perror("y16t: unable to lock file"); + return -1; + } + //tmp = y16t_db_remove(fd, x, y, z); tmp = -EOPNOTSUPP; if(tmp < 0) { @@ -171,12 +182,17 @@ int main(int argc, const char *argv[]) return -1; } - fd = open(dbfile, O_RDWR | O_NOCTTY); + fd = open(dbfile, O_RDONLY | O_NOCTTY); if(fd == -1) { perror("y16t: unable to open file"); return -1; } + if(flock(fd, LOCK_SH) == -1) { + perror("y16t: unable to lock file"); + return -1; + } + varname = 'y'; y16t_db_foreach_y(fd, x, y16t_cli_fecb, &varname); break; @@ -192,12 +208,17 @@ int main(int argc, const char *argv[]) return -1; } - fd = open(dbfile, O_RDWR | O_NOCTTY); + fd = open(dbfile, O_RDONLY | O_NOCTTY); if(fd == -1) { perror("y16t: unable to open file"); return -1; } + if(flock(fd, LOCK_SH) == -1) { + perror("y16t: unable to lock file"); + return -1; + } + varname = 'x'; y16t_db_foreach_x(fd, y, y16t_cli_fecb, &varname); break;