4

Can CreateFile() Open one file at the same time in two different thread


void new_function(void * what) {

HANDLE h = CreateFile("c:\\tmp", GENERIC_ALL,FILE_SHARE_WRITE | 
                  FILE_SHARE_READ , NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

if (h == INVALID_HANDLE_VALUE)
{
    DWORD d = GetLastError();
    return ;
}
Sleep(10000);

}

int main() {

HANDLE h = CreateFile("c:\\tmp", GENERIC_ALL,FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

Sleep(10000);
return 1;

}


every time it exits at the GetLastError position. and the error is ERROR_SHARING_VIOLATION (32, "The process cannot access the file because it is being used by another process.")

if i canot share open the file, then what is the use of the FILE_SHARE_WRITE | FILE_SHARE_READ

thanx

The program environment is Win32 Vs2003

Nickolay
  • 31,095
  • 13
  • 107
  • 185
StevenWang
  • 3,625
  • 4
  • 30
  • 40
  • You need to say which language, which operating system, which version. – John Saunders Oct 16 '09 at 05:14
  • Looks like C to me. CreateFile is a Win32() API. You would have liked him to better tag it... He is a 63 reputation user who joined 24 days ago. Be peaceful. Thanks for retagging it. – Heath Hunnicutt Oct 16 '09 at 05:16

1 Answers1

14

The file handle is always shared between threads. All you will need to do is merely use the handle as normal, but on two threads.

Your second call to CreateFile() fails because you ask for more access, GENERIC_ALL, than you allow for shared access, FILE_SHARE_WRITE | FILE_SHARE_READ.

If you instead requested only GENERIC_READ | GENERIC_WRITE, it would succeed.

The CreateFile() behavior will be the same if you call it on a single thread.

Heath Hunnicutt
  • 18,667
  • 3
  • 39
  • 62