Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 20.8 Source Code 761


171 /*
172 * Allocate an index buffer and a data buffer.
173 * +2 for newline and null at end.
174 */
175 if ((db->idxbuf = malloc(IDXLEN_MAX + 2)) == NULL)
176 err_dump("_db_alloc: malloc error for index buffer");
177 if ((db->datbuf = malloc(DATLEN_MAX + 2)) == NULL)
178 err_dump("_db_alloc: malloc error for data buffer");
179 return(db);
180 }
181 /*
182 * Relinquish access to the database.
183 */
184 void
185 db_close(DBHANDLE h)
186 {
187 _db_free((DB *)h); /* closes fds, free buffers & struct */
188 }
189 /*
190 * Free up a DB structure, and all the malloc’ed buffers it
191 * may point to. Also close the file descriptors if still open.
192 */
193 static void
194 _db_free(DB *db)
195 {
196 if (db->idxfd >= 0)
197 close(db->idxfd);
198 if (db->datfd >= 0)
199 close(db->datfd);

[171 – 180] We allocate space for buffers for the index and data files. The buffer sizes are
defined inapue_db.h.Anenhancement to the database library would be
to allow these buffers to expand as required. Wecould keep track of the size
of these two buffers and callreallocwhenever we find we need a bigger
buffer.Finally, we return a pointer to theDBstructurethat we allocated.
[181 – 188] Thedb_closefunction is a wrapper that casts a database handle to aDB
structurepointer,passing it to_db_freeto release any resources and free
theDBstructure.
[189 – 199] The_db_freefunction is called bydb_open if an error occurs while
opening the index file or data file and is also called bydb_closewhen an
application is done using the database. If the file descriptor for the database
index file is valid, we close it. The same is done with the file descriptor for
the data file. (Recall that when we allocate a new DB structurein
_db_alloc, we initialize each file descriptor to−1. If we areunable to open
one of the database files, the corresponding file descriptor will still be set to
−1, and we will avoid trying to close it.)
Free download pdf