Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 20.8 Source Code 771


472 /*
473 * Write a data record. Called by _db_dodelete (to write
474 * the record with blanks) and db_store.
475 */
476 static void
477 _db_writedat(DB *db, const char *data, off_t offset, int whence)
478 {
479 struct iovec iov[2];
480 static char newline=NEWLINE;
481 /*
482 * If we’re appending, we have to lock before doing the lseek
483 * and write to make the two an atomic operation. If we’re
484 * overwriting an existing record, we don’t have to lock.
485 */
486 if (whence == SEEK_END) /* we’re appending, lock entire file */
487 if (writew_lock(db->datfd, 0, SEEK_SET, 0) < 0)
488 err_dump("_db_writedat: writew_lock error");
489 if ((db->datoff = lseek(db->datfd, offset, whence)) == -1)
490 err_dump("_db_writedat: lseek error");
491 db->datlen=strlen(data) + 1; /* datlen includes newline */
492 iov[0].iov_base=(char *) data;
493 iov[0].iov_len =db->datlen - 1;
494 iov[1].iov_base=&newline;
495 iov[1].iov_len =1;
496 if (writev(db->datfd, &iov[0], 2) != db->datlen)
497 err_dump("_db_writedat: writev error of data record");
498 if (whence == SEEK_END)
499 if (un_lock(db->datfd, 0, SEEK_SET, 0) < 0)
500 err_dump("_db_writedat: un_lock error");
501 }

[472 – 491] We call_db_writedatto write a data record. When we delete a record, we
use_db_writedatto overwrite the recordwith blanks;_db_writedat
doesn’t need to lock the data file, becausedb_deletehas write locked the
hash chain for this record. Thus, no other process could be reading or
writing this particular data record. When we coverdb_storelater in this
section, we’ll encounter the case in which_db_writedatis appending to
the data file and has to lock it.
We seek to the location where we want to write the data record. The amount
to write is the recordsize plus 1 byte for the terminating newline we add.
[492 – 501] We set up theiovecarray and callwritevto write the data recordand
newline. Wecan’t assume that the caller’s buffer has room at the end for us
to append the newline, so we write the newline from a separate buffer.Ifwe
areappending a record to the file, we release the lock we acquired earlier.
Free download pdf