1
0
mirror of https://gitlab.com/80486DX2-66/gists synced 2025-01-10 08:27:48 +05:30

reverse-ramdisk.c: add mutex in TempFile struct

This commit is contained in:
パチュリー・ノーレッジ 2024-01-03 20:05:14 +03:00
parent e70d50cee4
commit 8de851ad79
Signed by: 80486DX2-66
GPG Key ID: 83631EF27054609B

View File

@ -5,7 +5,6 @@ C programming idea: Handling temporary files like memory allocations (allocating
Warning: The current result is quick and dirty. Not for educational or
production purposes.
Warning: The functions are not thread-safe.
GCC/Clang/TCC: Compile with -DTEST to set macro TEST as defined, with -DDEBUG
to enable debug mode
@ -16,6 +15,7 @@ To-Do: Add thread-safe versions of functions (use postfix `_r`)
#include <errno.h>
#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@ -40,6 +40,7 @@ To-Do: Add thread-safe versions of functions (use postfix `_r`)
} while (0)
typedef struct {
bool locked;
int ID;
char* file_path;
#if IS_POSIX
@ -96,6 +97,7 @@ int tf_alloc(size_t n, size_t type_size) {
}
// Assign the ID, file path, file handler
temp_file->locked = false;
temp_file->ID = num_temp_files;
temp_file->file_path = strdup(file_path);
temp_file->file = file;
@ -120,6 +122,12 @@ int tf_alloc(size_t n, size_t type_size) {
int tf_free(int ID) {
size_t index = (size_t) ID;
if (temp_files[index].locked) {
errno = EBUSY;
return -1;
}
temp_files[index].locked = true;
#if IS_POSIX
close(temp_files[index].file);
#else
@ -147,12 +155,20 @@ int tf_free(int ID) {
return -1;
}
temp_files[index].locked = false;
return 0;
}
int tf_write(int ID, size_t offset, void* src, size_t data_size) {
size_t index = (size_t) ID;
if (temp_files[index].locked) {
errno = EBUSY;
return -1;
}
temp_files[index].locked = true;
#if IS_POSIX
// Check file handler for -1
int file = temp_files[index].file;
@ -199,12 +215,20 @@ int tf_write(int ID, size_t offset, void* src, size_t data_size) {
fflush(file);
#endif
temp_files[index].locked = false;
return 0;
}
int tf_read(int ID, size_t offset, void* dest, size_t data_size) {
size_t index = (size_t) ID;
if (temp_files[index].locked) {
errno = EBUSY;
return -1;
}
temp_files[index].locked = true;
#if IS_POSIX
int file = temp_files[index].file;
if (file == -1)
@ -264,6 +288,9 @@ int tf_read(int ID, size_t offset, void* dest, size_t data_size) {
printf("'\n");
fflush(stdout);
#endif
temp_files[index].locked = false;
return 0;
}