Implement lock files on Windows

Source: Internet
Author: User

Lock files can be used for inter-process communication. For example, if we want to share some resources with multiple processes, one program is used to release the updated resources, while other programs can use the latest resources to do some things. Since the reader program may be some batch files, it is unlikely that some advanced synchronization tools will be used to lock the resources we need to release. In this way, using lock files will be a direct and simple method.

We need to use lock files to implement a simple reader-writer lock, that is, when someone needs to perform a write operation, all other operations are not allowed. However, when a user performs a read operation, the write operation is still prohibited only when the read operation is allowed.

#include <windows.h> #include <cstdlib> #include <cstring> #include <iostream> #include <tchar.h> enum lock_mode {    lm_shareread,    lm_exclusive,    lm_count};int main(int argc, char** argv) {    if (argc >= 2) {        lock_mode m;        DWORD dwAccess;        DWORD dwShareMode;        if (strcmp(argv[1], "-r") == 0) {            dwAccess = GENERIC_READ;            dwShareMode = FILE_SHARE_READ | FILE_SHARE_DELETE; // share read            m = lm_shareread;        } else if (strcmp(argv[1], "-w") == 0) {            dwAccess = GENERIC_WRITE;            dwShareMode = FILE_SHARE_DELETE; // do not share read or write, exclusive            m = lm_exclusive;        } else {            std::cerr << "invalid argument/n";            return EXIT_FAILURE;        }        HANDLE hFile;        hFile = CreateFile(_T("lock"), dwAccess, dwShareMode, NULL,                           OPEN_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL);        if (hFile != INVALID_HANDLE_VALUE) {#ifdef _DEBUG            char c;            std::cin >> c;#endif            if (m == lm_shareread) {                std::cout << "read complete/n";            } else {                std::cout << "write complete/n";            }            CloseHandle(hFile);            return EXIT_SUCCESS;        } else {            if (m == lm_shareread) {                std::cerr << "Cannot read/n";            } else {                std::cerr << "Cannot write/n";            }            std::cerr << "Error code: " << GetLastError() << std::endl;            return EXIT_FAILURE;        }    } else {        std::cerr << "no arguments specified/n";        return EXIT_FAILURE;    }}

This program accepts two types of parameters-R,-W,-R for reading and-W for writing. You can try to simulate two types of File locks.

Here we use file_flag_delete_on_close. Because file locks are usually temporary files, when the last file handle is closed, the file will be automatically deleted. file_attribute_temporary indicates that this is a temporary file, writing data to it does not need to be written back to the disk (it does not matter if it is not added, because there is no access operation here ).

 

We used open_always when creating the file. If the object does not exist, you must create a file. If the object already exists, you must open the file directly. If they are separated into two operations: 1. test whether a file exists 2. Open or create a file

There will be race condition. Suppose we find that the file does not exist after the test, then we decided to create the file, but at this time another program also found that the file does not exist and is also ready to create the file, then one of the Creation operations will inevitably fail, here we want atomic operation, and open_always just guarantees this situation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.