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.

a loop until all the data is read. A timeout could be applied to the read operation to<br />

cause the incomplete lock to be treated as stale. This race condition will only occur if<br />

a process creates the lock file without writing any data to it. This could be caused by<br />

an attacker, or it could occur because the process is terminated at precisely the right<br />

time so that it doesn’t get the chance to write its ID to the lock file.<br />

Once the process ID is read from the lock file, an attempt to send the process a signal<br />

of 0 is made. If the signal cannot be sent because the process does not exist, the<br />

call to kill( ) will return failure, and errno will be set to ESRCH. If this happens, the<br />

lock file is stale, and it can be removed. This is where the race condition discussed<br />

earlier occurs. The lock file is removed, the attempt counter is decremented, and the<br />

loop is restarted.<br />

Between the time that kill( ) returns failure with an ESRCH error code and the time<br />

that unlink( ) is called to remove the lock file, another process could successfully<br />

delete the lock file and begin creating a new one. If this happens, the process will<br />

successfully write its process ID to the now deleted lock file and assume that it has<br />

the lock. It will not have the lock, though, because this process will have deleted the<br />

lock file the other process was creating. For this reason, after the lock file is created,<br />

the process must attempt to read the lock file and compare process IDs. If the process<br />

ID in the lock file is the same as the process making the comparison, the lock<br />

was successfully obtained.<br />

See Also<br />

Recipe 2.4<br />

2.10 Synchronizing Resource Access Across<br />

Processes on Windows<br />

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

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

resource.<br />

Solution<br />

Use a named mutex (mutually exclusive lock) to synchronize access to the resource.<br />

Discussion<br />

Coordinating access to a shared resource between multiple processes on Windows is<br />

much simpler and much more elegant than it is on Unix. For maximum portability<br />

Synchronizing Resource Access Across Processes on Windows | 63<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!