Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

780 ADatabase Library Chapter 20


751 /*
752 * We read lock the free list so that we don’t read
753 *arecord in the middle of its being deleted.
754 */
755 if (readw_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
756 err_dump("db_nextrec: readw_lock error");

757 do {
758 /*
759 * Read next sequential index record.
760 */
761 if (_db_readidx(db, 0) < 0) {
762 ptr =NULL; /* end of index file, EOF */
763 goto doreturn;
764 }

765 /*
766 * Check if key is all blank (empty record).
767 */
768 ptr=db->idxbuf;
769 while ((c = *ptr++) != 0 && c == SPACE)
770 ; /* skip until null byte or nonblank */
771 } while (c == 0); /* loop until a nonblank key is found */

772 if (key != NULL)
773 strcpy(key, db->idxbuf); /* return key */
774 ptr=_db_readdat(db); /* return pointer to data buffer */
775 db->cnt_nextrec++;

776 doreturn:
777 if (un_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
778 err_dump("db_nextrec: un_lock error");
779 return(ptr);
780 }

[751 – 756] We first need to read lock the free list so that no other processes can remove
arecordwhile we arereading it.

[757 – 771] We call_db_readidxto read the next record. Wepass in an offset of 0 to
tell_db_readidxto continue reading from the current offset. Since we are
reading the index file sequentially, we can come across records that have
been deleted.We want to return only valid records, so we skip any record
whose key is all spaces (recall that_db_dodeleteclears a key by setting it
to all spaces).
[772 – 780] When we find a valid key, we copy it to the caller ’s buffer if one was
supplied. Then we read the data recordand set the return value to point to
the internal buffer containing the data record. Weincrement a statistics
counter,unlock the free list, and return the pointer to the data record.
Free download pdf