├── .github └── FUNDING.yml ├── .gitignore ├── CMakeLists.txt ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── include ├── FileLockFactory.hpp ├── FileLockStrategy.hpp ├── UnixFileLock.hpp └── WindowsFileLock.hpp └── src └── main.cpp /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [kagancansit] 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | *.gch 10 | *.pch 11 | 12 | 13 | # Precompiled Headers 14 | *.gch 15 | *.pch 16 | 17 | # Compiled Dynamic libraries 18 | *.so 19 | *.dylib 20 | *.dll 21 | 22 | # Fortran module files 23 | *.mod 24 | *.smod 25 | 26 | # Compiled Static libraries 27 | *.lai 28 | *.la 29 | *.a 30 | *.lib 31 | 32 | # Executables 33 | *.exe 34 | *.out 35 | *.app 36 | 37 | # IDE Specific folder 38 | nbproject/ 39 | private/ 40 | .vscode 41 | 42 | # Temp 43 | .dep.inc 44 | 45 | # Build folder 46 | build 47 | 48 | 49 | 50 | #draw.io 51 | *.drawio 52 | *.drawio.bkp -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | project(CrossCompatibleFileLock) 3 | 4 | set(CMAKE_CXX_STANDARD 17) 5 | 6 | # Include directories 7 | include_directories(include) 8 | 9 | # Source files 10 | set(SOURCES 11 | src/main.cpp 12 | ) 13 | 14 | # Executable 15 | add_executable(FileLockExample ${SOURCES}) 16 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | kagancansit@hotmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Cross-Compatible FileLock 2 | 3 | First off, thank you for considering contributing to Cross-Compatible FileLock! Your help is highly appreciated and essential for the growth and improvement of this project. 4 | 5 | The following is a set of guidelines for contributing to the project. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. 6 | 7 | ## Table of Contents 8 | 9 | 1. [How to Report a Bug](#how-to-report-a-bug) 10 | 2. [How to Submit a Feature Request](#how-to-submit-a-feature-request) 11 | 3. [How to Contribute Code](#how-to-contribute-code) 12 | 4. [Code of Conduct](#code-of-conduct) 13 | 14 | ## How to Report a Bug 15 | 16 | If you find a bug in the project, please create an issue on GitHub. Before creating an issue, please check if the issue has already been reported. 17 | 18 | ### Steps to Report a Bug 19 | 20 | 1. **Check Existing Issues**: Ensure your issue hasn’t already been reported. 21 | 2. **Create a New Issue**: If no existing issue covers your bug, create a new issue. 22 | 3. **Provide Detailed Information**: Include as much detail as possible: 23 | - A descriptive title 24 | - Steps to reproduce the bug 25 | - Expected behavior 26 | - Actual behavior 27 | - Environment (OS, Compiler, etc.) 28 | - Any relevant logs or screenshots 29 | 30 | ## How to Submit a Feature Request 31 | 32 | Feature requests are welcome. If you have an idea to improve the project, please create an issue on GitHub to discuss it. 33 | 34 | ### Steps to Submit a Feature Request 35 | 36 | 1. **Check Existing Issues**: Ensure your feature request hasn’t already been suggested. 37 | 2. **Create a New Issue**: If no existing issue covers your feature request, create a new issue. 38 | 3. **Provide Detailed Information**: Include as much detail as possible: 39 | - A descriptive title 40 | - A detailed explanation of the feature 41 | - Why this feature would be useful 42 | - Any code snippets or examples that help illustrate the feature 43 | 44 | ## How to Contribute Code 45 | 46 | We welcome contributions in the form of bug fixes, new features, and improvements. Please follow these steps to contribute code: 47 | 48 | ### Steps to Contribute Code 49 | 50 | 1. **Fork the Repository**: Fork the repo on GitHub and clone your fork locally. 51 | ```sh 52 | git clone https://github.com/your-username/Cross-Compatible-FileLock.git 53 | cd Cross-Compatible-FileLock 54 | ``` 55 | 56 | 2. **Create a Branch**: Create a new branch for your work. 57 | ```sh 58 | git checkout -b feature-or-bugfix-description 59 | ``` 60 | 61 | 3. **Make Changes**: Implement your changes in the new branch. Follow the style guides and ensure your code is well-documented. 62 | 63 | 4. **Commit Your Changes**: Commit your changes with a descriptive commit message. 64 | ```sh 65 | git add . 66 | git commit -m "Description of the changes" 67 | ``` 68 | 69 | 5. **Push to Your Fork**: Push your changes to your fork on GitHub. 70 | ```sh 71 | git push origin feature-or-bugfix-description 72 | ``` 73 | 74 | 6. **Create a Pull Request**: Create a pull request on the original repository. Provide a detailed description of your changes and any related issue numbers. 75 | 76 | ### Pull Request Guidelines 77 | 78 | - Ensure your code compiles and work. 79 | - Follow the existing code style and structure. 80 | - Provide a clear and detailed description of the changes. 81 | - Reference any relevant issues in your pull request description. 82 | - Remember that you are addressing a community in your description and code. 83 | 84 | ### Commit Messages 85 | 86 | - Use the present tense ("Add feature" not "Added feature"). 87 | - Use the imperative mood ("Move cursor to..." not "Moves cursor to..."). 88 | - Limit the first line to 72 characters or less. 89 | - Reference issues and pull requests liberally. 90 | 91 | ### Code of Conduct 92 | Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. 93 | 94 | ## Thank You! 95 | 96 | Thank you for your interest in contributing to Cross-Compatible FileLock. Your efforts and time are greatly appreciated and will help make this project better for everyone! 97 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Kağan Can Şit 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cross-Compatible File Lock for Linux and Windows Operating Systems 2 | 3 | ## What is File Lock, and What Is It Used For? 4 | File Lock is a synchronization mechanism that allows only one process to access a file at a time. It ensures proper ordering and synchronization between processes trying to access the same file, operating at the OS level rather than in memory. It is commonly used in databases, shared file access, log files, file management operations, and parallel programming. 5 | 6 | ## Key Considerations 7 | - Long file locking periods can cause other processes to wait, potentially leading to performance issues. 8 | - File locks must be managed carefully on the client side. Failing to release locked files can lead to persistent issues in the system. 9 | 10 | As the number of processes and their durations increase, the complexity of using File Lock can also increase. Therefore, it's essential to carefully evaluate your needs and your application's requirements before implementing File Lock. 11 | 12 | ## Purpose of Code in This Repository 13 | This project provides a cross-platform file locking mechanism for Linux and Windows using C++. It abstracts platform-specific details using the Strategy and Factory design patterns, offering a unified interface for file lock operations. 14 | 15 | **IMPORTANT!** 16 | 17 | **The implementation waits for the file to be unlocked if it is already locked. You can modify the flags to issue an error instead and manage your process accordingly.** 18 | 19 | ## Documentation for File Lock Usage in Windows and Linux 20 | For file locking operations in Windows operating systems, you need to include the "windows.h" header. For general usage methods and information about this library, please refer to the following documentation. 21 | 22 | [Windows Documentation - Learn Microsoft](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfile) 23 | 24 | Linux operating systems have multiple headers for file locking operations. Flock is used in the old period, Fcntl is new. For general usage methods and information regarding these contents, see the documents below. 25 | 26 | [Linux Documentation - GNU.org](https://www.gnu.org/software/libc/manual/html_node/File-Locks.html) 27 | 28 | [Linux Documentation - Man Page](https://man7.org/linux/man-pages/man2/fcntl.2.html) 29 | 30 | ## Features 31 | 32 | - Platform-specific file locking implementations (`UnixFileLock` for Linux and `WindowsFileLock` for Windows). 33 | - Factory pattern to abstract the creation of platform-specific file lock instances. 34 | - Modern C++ features like std::unique_ptr for memory management 35 | 36 | ## Requirements 37 | - C++ compiler (e.g., g++ or Visual C++) (C++ 17 or higher) 38 | - [CMake](https://cmake.org/) (at least version 3.0) 39 | - [Git](https://git-scm.com/) 40 | 41 | ## Installation 42 | To use the code, simply import the header and cpp files into your project as needed. If you want to try the basic example on the `main.cpp` function, you can follow these steps: 43 | 44 | 1. Clone the repository: 45 | ```sh 46 | git clone https://github.com/KaganCanSit/Cross-Compatible-FileLock-Windows-and-Linux.git 47 | cd Cross-Compatible-FileLock-Windows-and-Linux 48 | ``` 49 | 50 | 2. Build the project using CMake: 51 | ```sh 52 | mkdir build 53 | cd build 54 | cmake .. 55 | make 56 | ``` 57 | 58 | 3. Run the executable: 59 | ```sh 60 | ./FileLockExample 61 | ``` 62 | 63 | ## Contribution 64 | I have made an effort to create this repository thoughtfully, but errors may still occur. Please feel free to contribute and give constructive feedback. 65 | 66 | If you would like to contribute, you can follow the [CONTRIBUTING](CONTRIBUTING.md) instructions. 67 | 68 | ## License 69 | This project is licensed under the MIT License. For details, see the [LICENSE](https://github.com/KaganCanSit/Cross-Compatible-FileLock-Windows-and-Linux/blob/main/LICENSE) 70 | file. 71 | -------------------------------------------------------------------------------- /include/FileLockFactory.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include "FileLockStrategy.hpp" 7 | #include "UnixFileLock.hpp" 8 | #include "WindowsFileLock.hpp" 9 | 10 | // Use the following code to include the necessary header files for the operating system. Factory Pattern is used to create the necessary object. 11 | class FileLockFactory { 12 | public: 13 | static std::unique_ptr createFileLock(const std::string& filePath) { 14 | #if defined(_WIN32) || defined(_WIN64) 15 | return std::make_unique(filePath); 16 | #elif defined(__linux) || defined(__linux__) 17 | return std::make_unique(filePath); 18 | #else 19 | return nullptr; 20 | #endif 21 | }; 22 | }; 23 | -------------------------------------------------------------------------------- /include/FileLockStrategy.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | //You can use this interface to separate File Lock libraries according to different operating system libraries. 6 | // Strategy Pattern - Strategy Interface 7 | class FileLockStrategy { 8 | public: 9 | virtual ~FileLockStrategy() = default; 10 | virtual bool lock() noexcept= 0; 11 | virtual void unlock() noexcept = 0; 12 | }; 13 | 14 | // Strategy Pattern - Context Class 15 | class FileLockContext { 16 | public: 17 | FileLockContext(std::unique_ptr strategy) : mStrategy (std::move(strategy)){}; 18 | 19 | inline bool lock() { 20 | return mStrategy->lock(); 21 | } 22 | 23 | inline void unlock() { 24 | mStrategy->unlock(); 25 | } 26 | private: 27 | std::unique_ptr mStrategy; 28 | }; 29 | -------------------------------------------------------------------------------- /include/UnixFileLock.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | /* 4 | * In the Linux operating system, more than one header must be defined for file lock operations. 5 | * Flock may be preferred as the old one, and fctnl may be preferred as the more recent one. 6 | * Be sure to review the documentation below to get information about generally used methods and this library. 7 | * https://www.gnu.org/software/libc/manual/html_node/File-Locks.html 8 | * https://man7.org/linux/man-pages/man2/fcntl.2.html 9 | */ 10 | 11 | #if defined(__linux) || defined(__linux__) 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | #include "FileLockStrategy.hpp" 19 | 20 | class UnixFileLock final : public FileLockStrategy { 21 | public: 22 | explicit inline UnixFileLock(const std::string& filePath) : filePath(filePath), fileDescriptor(-1) {}; 23 | ~UnixFileLock() noexcept override { 24 | unlock(); 25 | }; 26 | 27 | inline bool lock() noexcept override { 28 | fileDescriptor = open(filePath.c_str(), O_RDWR | O_CREAT, 0666); 29 | if (fileDescriptor == -1) { 30 | return false; 31 | } 32 | return (flock(fileDescriptor, LOCK_EX) == 0); 33 | }; 34 | 35 | inline void unlock() noexcept override 36 | { 37 | if (fileDescriptor != -1) 38 | { 39 | flock(fileDescriptor, LOCK_UN); 40 | close(fileDescriptor); 41 | fileDescriptor = -1; 42 | } 43 | }; 44 | 45 | private: 46 | std::string filePath; 47 | int fileDescriptor; 48 | }; 49 | 50 | #endif // UNIXFILELOCK_H -------------------------------------------------------------------------------- /include/WindowsFileLock.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | /* 4 | * For file lock operations in the Windows operating system, it is sufficient to have the "windows.h" header defined. 5 | * Be sure to review the documentation below to get information about generally used methods and this library. 6 | * https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfile 7 | */ 8 | 9 | #if defined(_WIN32) || defined(_WIN64) 10 | #include 11 | #include 12 | 13 | #include "FileLockStrategy.hpp" 14 | 15 | class WindowsFileLock final : public FileLockStrategy { 16 | public: 17 | explicit inline WindowsFileLock(const std::string& filePath) : filePath(filePath), fileHandle(INVALID_HANDLE_VALUE) {} 18 | 19 | ~WindowsFileLock() noexcept override{ 20 | unlock(); 21 | }; 22 | 23 | inline bool lock() noexcept override{ 24 | std::wstring wideFilePath(filePath.begin(), filePath.end()); 25 | 26 | fileHandle = CreateFile(wideFilePath.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 27 | if (fileHandle == INVALID_HANDLE_VALUE) { 28 | return false; 29 | } 30 | return true; 31 | }; 32 | 33 | inline void unlock() noexcept override { 34 | if (fileHandle != INVALID_HANDLE_VALUE) { 35 | CloseHandle(fileHandle); 36 | fileHandle = INVALID_HANDLE_VALUE; 37 | } 38 | }; 39 | 40 | private: 41 | std::string filePath; 42 | HANDLE fileHandle; 43 | }; 44 | #endif // _WIN32 || _WIN64 45 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "FileLockFactory.hpp" 6 | 7 | int main() { 8 | 9 | std::unique_ptr fileLock = std::make_unique(FileLockFactory::createFileLock("test.txt")); // Write the file path parameters 10 | if(fileLock == nullptr){ 11 | std::cerr << "Failed to create file lock object. Unsupported OS!" << std::endl; 12 | return 1; 13 | } 14 | 15 | if(!fileLock->lock()){ 16 | std::cerr << "Failed to lock the file." << std::endl; 17 | return 1; 18 | } 19 | 20 | std::cout << "File locked successfully." << std::endl; 21 | 22 | // Make operation on this area 23 | std::this_thread::sleep_for(std::chrono::seconds(5)); 24 | 25 | fileLock->unlock(); 26 | std::cout << "File unlocked successfully." << std::endl; 27 | 28 | return 0; 29 | } --------------------------------------------------------------------------------