Added acquire/release functions to reuse

This commit is contained in:
thematdev 2023-07-01 23:45:01 +03:00
parent 65096b1987
commit d5f0e478e1
Signed by: thematdev
GPG Key ID: D12878639B090D90
2 changed files with 45 additions and 20 deletions

View File

@ -13,6 +13,8 @@ OBJ_FILES := $(patsubst %.c,$(BD)/%.o,$(SRC_FILES))
OBJ_FILES := $(patsubst %.c,$(BD)/%.o,$(SRC_FILES))
SHARED_OBJ_FILES := $(patsubst %.c,$(SBD)/%.o,$(SRC_FILES))
CFLAGS ?= -O2 -ansi -pedantic
shared: $(SBD)/$(SHARED_LIB)
static: $(BD)/$(STATIC_LIB)

View File

@ -84,6 +84,43 @@ deserialize_header(int fd, CommentHeader *header)
/* TODO: validate driver_data_ptr */
FILE *
acquire_id_ctrl_file(char *id_ctrl_file_path)
{
FILE *retval;
int fd;
retval = NULL;
if (!(retval = fopen(id_ctrl_file_path, "r+"))) {
goto defer;
}
fd = fileno(retval);
if (lockf(fd, F_LOCK, 0) < 0) {
fclose(retval);
retval = NULL;
goto defer;
}
defer:
return retval;
}
int
release_id_ctrl_file(FILE *id_ctrl_file)
{
int fd;
fd = fileno(id_ctrl_file);
if (lockf(fd, F_ULOCK, 0) < 0) {
fclose(id_ctrl_file);
return -ENOLCK;
}
return fclose(id_ctrl_file);
}
int
unix_fs_driver_leave_comment(void *driver_data_ptr, const CommentHeader *header, const char *text)
{
@ -114,17 +151,7 @@ unix_fs_driver_leave_comment(void *driver_data_ptr, const CommentHeader *header,
goto defer;
}
id_ctrl_file = fopen(id_ctrl_file_path, "r+");
if (!id_ctrl_file) {
retval = -EIO;
goto defer;
}
id_ctrl_fd = fileno(id_ctrl_file);
if (lockf(id_ctrl_fd, F_LOCK, 0) < 0) {
id_ctrl_fd = -1;
if (!(id_ctrl_file = acquire_id_ctrl_file(id_ctrl_file_path))) {
retval = -EIO;
goto defer;
}
@ -162,21 +189,17 @@ unix_fs_driver_leave_comment(void *driver_data_ptr, const CommentHeader *header,
goto defer;
}
if (!(id_ctrl_file = freopen(id_ctrl_file_path, "w+", id_ctrl_file))) {
retval = -EIO;
goto defer;
}
rewind(id_ctrl_file);
fprintf(id_ctrl_file, "%d", max_id + 1); /* update id only on success */
retval = max_id + 1;
defer:
if (id_ctrl_fd >= 0) {
if (lockf(id_ctrl_fd, F_ULOCK, 0) < 0) {
fprintf(stderr, "Failed to release id control lock, aborting...\n");
if (id_ctrl_file) {
if (release_id_ctrl_file(id_ctrl_file) < 0) {
fprintf(stderr, "Failed to release id control file, aborting...\n");
abort();
}
}
if (id_ctrl_file) fclose(id_ctrl_file);
free(id_ctrl_file_path);
free(header_file_path);
free(text_file_path);