Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 356
Shaobo Wang Avatar asked Dec 17 '22 05:12

Shaobo Wang


1 Answers

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.

like image 144
Heath Hunnicutt Avatar answered Dec 19 '22 17:12

Heath Hunnicutt