Wiki Home

Vista Lock Reproduction Program Source


Namespace: WIN_COM_API
See Windows Vista File Locking Bug.
//
// lockfile.cpp: A little application to test locking characteristics.
//

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif

#include 
#include "windows.h"
#include 
using namespace std;

void PrintErrorMessage()
{
	LPVOID lpMsgBuf;
	DWORD dw = GetLastError();

	FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM,
		NULL,
		dw,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPTSTR) &lpMsgBuf,
		0, NULL );
	
	wcerr << "Failed with error: " << ((LPTSTR) lpMsgBuf) << endl;

	LocalFree(lpMsgBuf);
}

int _tmain(int argc, _TCHAR* argv[])
{
	if (argc < 2) {
		cerr << "Usage: lockfile " << endl;
		return 1;
	} else if (argc > 2) {
		cerr << "Too many arguments." << endl;
		cerr << "Usage: lockfile " << endl;
		return 1;
	}
	wcerr << _T("Opening/creating file: ") << argv[1] << endl;
	HANDLE hFile;
	hFile =
		CreateFile(
		argv[1],
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,
		OPEN_ALWAYS,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	if (hFile != INVALID_HANDLE_VALUE) {
		cerr << "File opened." << endl;
	} else {
		cerr << "File could not be opened. Aborting." << endl;
		PrintErrorMessage();
		return 1;
	}
	
	cerr << "Locking file..." << endl;
	OVERLAPPED areaToLock;
	bool locked;
	for (;;) {
		ZeroMemory(&areaToLock, sizeof(areaToLock));
		if (locked = (LockFileEx(hFile, LOCKFILE_FAIL_IMMEDIATELY | LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &areaToLock) != 0)) {
			cerr << "File locked." << endl;
			break;
		} else {
			cerr << "File could not be locked. Retrying in one second... (Ctrl-C to cancel)" << endl;
			Sleep(1000);
		}
	}
	
	if (locked) {
		cerr << "Press [enter] to continue..." << endl;
		cin.get();
		
		cerr << "Unlocking file..." << endl;
		if (UnlockFileEx(hFile, NULL, 1, 0, &areaToLock)){
			cerr << "File unlocked." << endl;
		} else {
			cerr << "File could not be unlocked." << endl;
			PrintErrorMessage();
		}
	}
	
	cerr << "Closing file handle..." << endl;
	if (CloseHandle(hFile)) {
		cerr << "File closed." << endl;
	} else {
		cerr << "File could not be closed." << endl;
		PrintErrorMessage();
	}

	return 0;
}


---
Contributors: Peter Crabtree
( Topic last updated: 2012.02.28 09:32:03 PM )