sem_close.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* Copyright (C) 2002, 2003 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <search.h>
  17. #include <sys/mman.h>
  18. #include "semaphoreP.h"
  19. /* Global variables to parametrize the walk function. This works
  20. since we always have to use locks. And we have to use the twalk
  21. function since the entries are not sorted wrt the mapping
  22. address. */
  23. static sem_t *the_sem;
  24. static struct inuse_sem *rec;
  25. static void
  26. walker (const void *inodep, const VISIT which, const int depth)
  27. {
  28. struct inuse_sem *nodep = *(struct inuse_sem **) inodep;
  29. if (nodep->sem == the_sem)
  30. rec = nodep;
  31. }
  32. int
  33. sem_close (
  34. sem_t *sem)
  35. {
  36. int result = 0;
  37. /* Get the lock. */
  38. lll_lock (__sem_mappings_lock, LLL_PRIVATE);
  39. /* Locate the entry for the mapping the caller provided. */
  40. rec = NULL;
  41. the_sem = sem;
  42. twalk (__sem_mappings, walker);
  43. if (rec != NULL)
  44. {
  45. /* Check the reference counter. If it is going to be zero, free
  46. all the resources. */
  47. if (--rec->refcnt == 0)
  48. {
  49. /* Remove the record from the tree. */
  50. (void) tdelete (rec, &__sem_mappings, __sem_search);
  51. result = munmap (rec->sem, sizeof (sem_t));
  52. free (rec);
  53. }
  54. }
  55. else
  56. {
  57. /* This is no valid semaphore. */
  58. result = -1;
  59. __set_errno (EINVAL);
  60. }
  61. /* Release the lock. */
  62. lll_unlock (__sem_mappings_lock, LLL_PRIVATE);
  63. return result;
  64. }