1 /*- 2 * Copyright (c) 1990 The Regents of the University of California. 3 * All rights reserved. 4 * 5 * %sccs.include.redist.c% 6 */ 7 8 #if defined(LIBC_SCCS) && !defined(lint) 9 static char sccsid[] = "@(#)rec_close.c 5.10 (Berkeley) 03/25/93"; 10 #endif /* LIBC_SCCS and not lint */ 11 12 #include <sys/types.h> 13 #include <sys/uio.h> 14 #include <sys/mman.h> 15 16 #include <errno.h> 17 #include <limits.h> 18 #include <stdio.h> 19 #include <unistd.h> 20 21 #include <db.h> 22 #include "recno.h" 23 24 /* 25 * __REC_CLOSE -- Close a recno tree. 26 * 27 * Parameters: 28 * dbp: pointer to access method 29 * 30 * Returns: 31 * RET_ERROR, RET_SUCCESS 32 */ 33 int 34 __rec_close(dbp) 35 DB *dbp; 36 { 37 BTREE *t; 38 int rval; 39 40 if (__rec_sync(dbp) == RET_ERROR) 41 return (RET_ERROR); 42 43 /* Committed to closing. */ 44 t = dbp->internal; 45 46 rval = RET_SUCCESS; 47 if (ISSET(t, BTF_MEMMAPPED) && munmap(t->bt_smap, t->bt_msize)) 48 rval = RET_ERROR; 49 50 if (!ISSET(t, BTF_RINMEM)) 51 if (ISSET(t, BTF_CLOSEFP)) { 52 if (fclose(t->bt_rfp)) 53 rval = RET_ERROR; 54 } else 55 if (close(t->bt_rfd)) 56 rval = RET_ERROR; 57 58 if (__bt_close(dbp) == RET_ERROR) 59 rval = RET_ERROR; 60 61 return (rval); 62 } 63 64 /* 65 * __REC_SYNC -- sync the recno tree to disk. 66 * 67 * Parameters: 68 * dbp: pointer to access method 69 * 70 * Returns: 71 * RET_SUCCESS, RET_ERROR. 72 */ 73 int 74 __rec_sync(dbp) 75 const DB *dbp; 76 { 77 struct iovec iov[2]; 78 BTREE *t; 79 DBT data, key; 80 off_t off; 81 recno_t scursor, trec; 82 int status; 83 84 t = dbp->internal; 85 86 if (ISSET(t, BTF_RDONLY | BTF_RINMEM) || !ISSET(t, BTF_MODIFIED)) 87 return (RET_SUCCESS); 88 89 /* Read any remaining records into the tree. */ 90 if (!ISSET(t, BTF_EOF) && t->bt_irec(t, MAX_REC_NUMBER) == RET_ERROR) 91 return (RET_ERROR); 92 93 /* Rewind the file descriptor. */ 94 if (lseek(t->bt_rfd, (off_t)0, SEEK_SET) != 0) 95 return (RET_ERROR); 96 97 iov[1].iov_base = "\n"; 98 iov[1].iov_len = 1; 99 scursor = t->bt_rcursor; 100 101 key.size = sizeof(recno_t); 102 key.data = &trec; 103 104 status = (dbp->seq)(dbp, &key, &data, R_FIRST); 105 while (status == RET_SUCCESS) { 106 iov[0].iov_base = data.data; 107 iov[0].iov_len = data.size; 108 if (writev(t->bt_rfd, iov, 2) != data.size + 1) 109 return (RET_ERROR); 110 status = (dbp->seq)(dbp, &key, &data, R_NEXT); 111 } 112 t->bt_rcursor = scursor; 113 if (status == RET_ERROR) 114 return (RET_ERROR); 115 if ((off = lseek(t->bt_rfd, (off_t)0, SEEK_CUR)) == -1) 116 return (RET_ERROR); 117 if (ftruncate(t->bt_rfd, off)) 118 return (RET_ERROR); 119 CLR(t, BTF_MODIFIED); 120 return (RET_SUCCESS); 121 } 122