Solved

File locking on Windows

Posted on 2006-06-28
17
472 Views
Last Modified: 2012-06-21
Hi!

How do I lock a file for writing on a windows machine? On Unix based system I can use the lockf() function but I haven't been able to find something similar to this on windows. I Need functions for locking,unlocking and checking if a file is locked or not. I will use this to prevent simultaneous writing attempts to a logfile.
0
Comment
Question by:sa9824
17 Comments
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17000075
HANDLE hHandle = CreateFile(
"test.txt",
GENERIC_WRITE,
0,                                         // don't share, that means it is locked by you.
NULL,                                    // no security
OPEN_EXISTING,                    // existing file only
FILE_ATTRIBUTE_NORMAL,     // normal file
NULL);                                  // no attr. template
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17000082
>> lockf
I saw the documentation of lockf, it says it loacks a section of the file.
If your purpose is to lock a section of a file then better use this function

BOOL LockFile(
  HANDLE hFile,                   // handle to file
  DWORD dwFileOffsetLow,          // low-order word of offset
  DWORD dwFileOffsetHigh,         // high-order word of offset
  DWORD nNumberOfBytesToLockLow,  // low-order word of length
  DWORD nNumberOfBytesToLockHigh  // high-order word of length
);
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17000087
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:sa9824
ID: 17000089
I want to lock the entire file, not just a part of it....
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17000332
Then use the CreateFile(...) as I showed above.
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17000366
0
 
LVL 16

Expert Comment

by:PaulCaswell
ID: 17004961
Hi sa9824,

If you are using a Microsoft C compiler you may find:

            FILE * f = _fsopen("File","a+",0x20/*_SH_DENYWR*/);

To check for access, either use the same function (you will get a NULL pointer returned) or use 'access'.

Paul
0
 
LVL 27

Expert Comment

by:Nopius
ID: 17007010
sa9824, use BOOL LockFile

with dwFileOffsetLow=0, dwFileOffsetHigh=0, nNumberOfBytesToLockLow=1, nNumberOfBytesToLockHigh=1
across all programs, that need to aguire/test lock that's enough
0
 

Author Comment

by:sa9824
ID: 17008001
HI I cant get this to work... Am I missing something?

int getFileLock(char *path){
      HANDLE hDevice;
      
      if(statForRFile(path)==0)
            return -1;
      else {
               hDevice = CreateFile(path,

                                    GENERIC_READ | GENERIC_WRITE,

                                    FILE_SHARE_READ | FILE_SHARE_WRITE,

                                    0,

                                    OPEN_EXISTING,

                                    FILE_FLAG_OVERLAPPED,

                                    0);

            if(hDevice == INVALID_HANDLE_VALUE){
                  CloseHandle(hDevice);
                  return 1;
            }else{
                  CloseHandle(hDevice);
                  return 0;
            }
      }

}


ANd locking function:

void lock(){
      HANDLE hDevice;
       
       hDevice = CreateFile(      _ALOGFILE,
                                           GENERIC_READ | GENERIC_WRITE,
                                           FILE_SHARE_READ | FILE_SHARE_WRITE,
                                           0,
                                           OPEN_EXISTING,
                                           FILE_FLAG_OVERLAPPED,
                                           0);



      if(hDevice == INVALID_HANDLE_VALUE){
            printf("INVALID HANDLE...");
      }
      
      LockFile(hDevice,0,0,1,1);

}
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17009652
As I said before also, set the third parameter to 0.
In that case it is locked and no other application will be able to access

CreateFile(path,
            GENERIC_READ | GENERIC_WRITE,
            0,                                             // This is not required FILE_SHARE_READ | FILE_SHARE_WRITE
            0,
            OPEN_EXISTING,
            FILE_FLAG_OVERLAPPED,
            0);
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17009701
After CreateFile you don't need LockFile to lock it.
0
 

Author Comment

by:sa9824
ID: 17009737
Ok, I will try this!
 Will this work between different instances of my application (there will be multiple instances running at the same time)?
0
 
LVL 12

Accepted Solution

by:
rajeev_devin earned 125 total points
ID: 17009745
Another thing in your implementation after using CreateFile(...) you are simply closing it both the cases.

>> if(hDevice == INVALID_HANDLE_VALUE){
>>               CloseHandle(hDevice); // It is closed if it is invalid
>>               return 1;
>>          }else{
>>               CloseHandle(hDevice); // It is closed even if it is valid
>>               return 0;
>>          }

To keep the lock don't close it until you are over. A better implementation would have been something like this


HANDLE getFileLock(char *path)
{
      if(0)
            return NULL;
      else {
            hDevice = CreateFile(path,
                  GENERIC_READ | GENERIC_WRITE,
                  0,
                  0,
                  OPEN_EXISTING,
                  FILE_FLAG_OVERLAPPED,
                  0);
            
            if(hDevice == INVALID_HANDLE_VALUE){
                  return NULL;
            }
      }

      return hDevice;
}

void fileUnlock(HANDLE hDev)
{
      CloseHandle(hDev);
}


HANDLE hDev = getFileLock(_ALOGFILE); // Lock the file

// Do your stuff

fileUnlock(hDev); // Unlock it when you are over

0
 

Author Comment

by:sa9824
ID: 17009762
It worked fine without the call to LockFile!

How can I release the lock on the file?
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17009768
>> Will this work between different instances of my application (there will be multiple instances running at the same >> time)?
Yes, it will work
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17009787
>> How can I release the lock on the file?
To release the lock simply use on that handle
CloseHandle(hDevice)
0
 

Author Comment

by:sa9824
ID: 17009859
Thanx rajeev_devin! You will get the points!
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

816 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now