///////////////////////////////////////////////////////////////////////////// // Creation 11/12/2003 // // // LOCKAPIWIN32.C // -------------- // // // Sylvain MARECHAL - sylvain.marechal1@libertysurf.fr ///////////////////////////////////////////////////////////////////////////// // // Locks with Win32 API (LockFile()) // Show that locks doesn't work in the same process // ///////////////////////////////////////////////////////////////////////////// #include #include #include void main() { HANDLE h1, h2; DWORD dwAccess = GENERIC_READ | GENERIC_WRITE; DWORD dwShare = FILE_SHARE_READ | FILE_SHARE_WRITE; DWORD dwCreate = OPEN_EXISTING; DWORD dwAtts = FILE_ATTRIBUTE_NORMAL; DWORD dwPos, dwPos2, dwPos3, dwLock; const char szFile[] = "testlock.txt"; // Open/create a file h1 = CreateFile( szFile, dwAccess, dwShare, NULL, CREATE_ALWAYS,//dwCreate, dwAtts, NULL); if( h1 == INVALID_HANDLE_VALUE ) { printf( "Can't open file (%d)\n", GetLastError() ); exit(1); } // lock 10 bytes at the end dwLock = 10; dwPos = SetFilePointer( h1, 0, NULL, FILE_END ); dwPos2 = SetFilePointer( h1, dwPos + dwLock, NULL, FILE_BEGIN ); SetEndOfFile( h1 ); dwPos3 = SetFilePointer( h1, 0, NULL, FILE_END ); printf( "dwPos=%d, dwPos2=%d, dwPos3=%d\n", dwPos, dwPos2, dwPos3 ); if( ! LockFile( h1, dwPos, 0, dwPos+dwLock, 0) ) { printf( "First call - Unable to lock the %d octets (Error=%d)\n", dwLock, GetLastError() ); printf( "Press a key to exit...\n" ); getch(); return; } // Message printf( "Press a key to continue ...\n" ); getch(); // open the same file for 2° time h2 = CreateFile( szFile, dwAccess, dwShare, NULL, dwCreate, dwAtts, NULL); if( h2 == INVALID_HANDLE_VALUE) { printf( "Unable to open '%s' (Error=%d)\n", szFile, GetLastError() ); return; } // Look if lock is possible dwPos = SetFilePointer( h2, 0, NULL, FILE_END ); if( ! LockFile( h2, 11, 0, 10, 0) ) { printf( "Secon call -Unable to lock the first 10 octets (Error=%d)\n", GetLastError() ); printf( "Press a key to exit...\n" ); getch(); return; } // Message printf( "Press a key to continue ...\n" ); getch(); }