use flock to provide basic concurrency protection

This commit is contained in:
Alain Zscheile 2023-01-04 08:52:23 +01:00
parent 5f6d6d4634
commit 7277868170

View file

@ -1,5 +1,6 @@
#include <y16t_db.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
@ -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;