21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

BOOL UnlockFile(HANDLE hFile, DWORD dwFileOffsetLow,<br />

DWORD dwFileOffsetHigh, DWORD nNumberOfBytesToUnlockLow,<br />

DWORD nNumberOfBytesToUnlockHigh);<br />

2.9 Synchronizing Resource Access Across<br />

Processes on Unix<br />

<strong>Problem</strong><br />

You want to ensure that two processes cannot simultaneously access the same<br />

resource, such as a segment of shared memory.<br />

Solution<br />

Use a lock file to signal that you are accessing the resource.<br />

Discussion<br />

Using a lock file to synchronize access to shared resources is not as simple as it<br />

sounds. Suppose that your program creates a lock file and then crashes. If this happens,<br />

the lock file will remain, and your program (as well as any other program that<br />

attempted to obtain the lock) will fail until someone manually removes the lock file.<br />

Obviously, this is undesirable. The solution is to store the process ID of the process<br />

holding the lock in the lock file. Other processes attempting to obtain the lock can<br />

then test to see whether the process holding the lock still exists. If it does not, the<br />

lock file is stale, it is safe to remove, and you can make another attempt to obtain the<br />

lock.<br />

Unfortunately, this solution is still not a perfect one. What happens if another process<br />

is assigned the same ID as the one stored in the stale lock file? The answer to<br />

this question is simply that no process can obtain the lock until the process with the<br />

stale ID terminates or someone manually removes the lock file. Fortunately, this case<br />

should not be encountered frequently.<br />

As a result of solving the stale lock problem, a new problem arises: there is now a<br />

race condition between the time the check for the existence of the process holding<br />

the lock is performed and the time the lock file is removed. The solution to this problem<br />

is to attempt to reopen the lock file after writing the new one to make sure that<br />

the process ID in the lock file is the same as the locking process’s ID. If it is, the lock<br />

is successfully obtained.<br />

The function presented below, spc_lock_file( ), requires a single argument: the<br />

name of the file to be used as the lock file. You must store the lock file in a “safe”<br />

directory (see Recipe 2.4) on a local filesystem. Network filesystems—versions of<br />

60 | Chapter 2: Access Control<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!