diff --git a/c-programming/reverse-ramdisk.c b/c-programming/reverse-ramdisk.c index 1300d45..f44280b 100644 --- a/c-programming/reverse-ramdisk.c +++ b/c-programming/reverse-ramdisk.c @@ -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 #include #include +#include #include #include #include @@ -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; }