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

Shaobo Wang picture Shaobo Wang · Oct 16, 2009 · Viewed 7.9k times · Source

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

Answer

Heath Hunnicutt picture Heath Hunnicutt · Oct 16, 2009

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.