views:

582

answers:

1

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

+6  A: 

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
Thanx very much.........i change `GENERIC_ALL` to `GENERIC_READ | GENERIC_WRITE`. i get the right answer
Macroideal
Yay, I am glad. Would you feel alright to accept my answer as the answer to your question? I like to see the green squares in my activity history and of course this is worth 15 reputation points. :)
Heath Hunnicutt
Also you can add FILE_SHARE_DELETE. It depends on what do you want from your file.
Sergius
You should not add FILE_SHARE_DELETE, because you want to request the least privilege needed.
Heath Hunnicutt
dw heath, i gave you some love for the concise answers
Matt Joiner