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.

NFS older than Version 3 in particular—may not necessarily support the O_EXCL flag<br />

to open( ). Further, because the ID of the process holding the lock is stored in the<br />

lock file and process IDs are not shared across machines, testing for the presence of<br />

the process holding the lock would be unreliable at best if the lock file were stored<br />

on a network filesystem.<br />

Three attempts are made to obtain the lock, with a pause of one second between<br />

attempts. If the lock cannot be obtained, the return value from the function is 0. If<br />

some kind of error occurs in attempting to obtain the lock, the return value is –1. If<br />

the lock is successfully obtained, the return value is 1.<br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

static int read_data(int fd, void *buf, size_t nbytes) {<br />

size_t toread, nread = 0;<br />

ssize_t result;<br />

do {<br />

if (nbytes - nread > SSIZE_MAX) toread = SSIZE_MAX;<br />

else toread = nbytes - nread;<br />

if ((result = read(fd, (char *)buf + nread, toread)) >= 0)<br />

nread += result;<br />

else if (errno != EINTR) return 0;<br />

} while (nread < nbytes);<br />

return 1;<br />

}<br />

static int write_data(int fd, const void *buf, size_t nbytes) {<br />

size_t towrite, written = 0;<br />

ssize_t result;<br />

do {<br />

if (nbytes - written > SSIZE_MAX) towrite = SSIZE_MAX;<br />

else towrite = nbytes - written;<br />

if ((result = write(fd, (const char *)buf + written, towrite)) >= 0)<br />

written += result;<br />

else if (errno != EINTR) return 0;<br />

} while (written < nbytes);<br />

return 1;<br />

}<br />

The two functions read_data( ) and write_data( ) are helper functions that ensure<br />

that all the requested data is read or written. If the system calls for reading or writing<br />

are interrupted by a signal, they are retried. Because such a small amount of data is<br />

being read and written, the data should all be written atomically, but all the data may<br />

not be read or written in a single call. These helper functions also handle this case.<br />

Synchronizing Resource Access Across Processes on Unix | 61<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!