sdbm_lock.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* Copyright 2000-2005 The Apache Software Foundation or its licensors, as
  2. * applicable.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "apr_file_info.h"
  17. #include "apr_file_io.h"
  18. #include "apr_sdbm.h"
  19. #include "sdbm_private.h"
  20. #include "sdbm_tune.h"
  21. /* NOTE: this function blocks until it acquires the lock */
  22. APU_DECLARE(apr_status_t) apr_sdbm_lock(apr_sdbm_t *db, int type)
  23. {
  24. apr_status_t status;
  25. if (!(type == APR_FLOCK_SHARED || type == APR_FLOCK_EXCLUSIVE))
  26. return APR_EINVAL;
  27. if (db->flags & SDBM_EXCLUSIVE_LOCK) {
  28. ++db->lckcnt;
  29. return APR_SUCCESS;
  30. }
  31. else if (db->flags & SDBM_SHARED_LOCK) {
  32. /*
  33. * Cannot promote a shared lock to an exlusive lock
  34. * in a cross-platform compatibile manner.
  35. */
  36. if (type == APR_FLOCK_EXCLUSIVE)
  37. return APR_EINVAL;
  38. ++db->lckcnt;
  39. return APR_SUCCESS;
  40. }
  41. /*
  42. * zero size: either a fresh database, or one with a single,
  43. * unsplit data page: dirpage is all zeros.
  44. */
  45. if ((status = apr_file_lock(db->dirf, type)) == APR_SUCCESS)
  46. {
  47. apr_finfo_t finfo;
  48. if ((status = apr_file_info_get(&finfo, APR_FINFO_SIZE, db->dirf))
  49. != APR_SUCCESS) {
  50. (void) apr_file_unlock(db->dirf);
  51. return status;
  52. }
  53. SDBM_INVALIDATE_CACHE(db, finfo);
  54. ++db->lckcnt;
  55. if (type == APR_FLOCK_SHARED)
  56. db->flags |= SDBM_SHARED_LOCK;
  57. else if (type == APR_FLOCK_EXCLUSIVE)
  58. db->flags |= SDBM_EXCLUSIVE_LOCK;
  59. }
  60. return status;
  61. }
  62. APU_DECLARE(apr_status_t) apr_sdbm_unlock(apr_sdbm_t *db)
  63. {
  64. if (!(db->flags & (SDBM_SHARED_LOCK | SDBM_EXCLUSIVE_LOCK)))
  65. return APR_EINVAL;
  66. if (--db->lckcnt > 0)
  67. return APR_SUCCESS;
  68. db->flags &= ~(SDBM_SHARED_LOCK | SDBM_EXCLUSIVE_LOCK);
  69. return apr_file_unlock(db->dirf);
  70. }