grent.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * grent.c - This file is part of the libc-8086/grp package for ELKS,
  4. * Copyright (C) 1995, 1996 Nat Friedman <ndf@linux.mit.edu>.
  5. * Copyright (C) 2001-2003 Erik Andersen <andersee@debian.org>
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Library General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Library General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Library General Public
  18. * License along with this library; if not, write to the Free
  19. * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. *
  21. */
  22. /*
  23. * setgrent(), endgrent(), and getgrent() are mutually-dependent functions,
  24. * so they are all included in the same object file, and thus all linked
  25. * in together.
  26. */
  27. #include <features.h>
  28. #include <unistd.h>
  29. #include <fcntl.h>
  30. #include <paths.h>
  31. #include <errno.h>
  32. #include "config.h"
  33. #ifdef __UCLIBC_HAS_THREADS__
  34. #include <pthread.h>
  35. static pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
  36. # define LOCK pthread_mutex_lock(&mylock)
  37. # define UNLOCK pthread_mutex_unlock(&mylock);
  38. #else
  39. # define LOCK
  40. # define UNLOCK
  41. #endif
  42. static int grp_fd = -1;
  43. void setgrent(void)
  44. {
  45. LOCK;
  46. if (grp_fd != -1)
  47. close(grp_fd);
  48. grp_fd = open(_PATH_GROUP, O_RDONLY);
  49. UNLOCK;
  50. }
  51. void endgrent(void)
  52. {
  53. LOCK;
  54. if (grp_fd != -1)
  55. close(grp_fd);
  56. grp_fd = -1;
  57. UNLOCK;
  58. }
  59. struct group *getgrent(void)
  60. {
  61. int ret;
  62. static struct group grp;
  63. static char line_buff[PWD_BUFFER_SIZE];
  64. LOCK;
  65. if (grp_fd == -1) {
  66. UNLOCK;
  67. return NULL;
  68. }
  69. ret = __getgrent_r(&grp, line_buff, sizeof(line_buff), grp_fd);
  70. if (ret == 0) {
  71. UNLOCK;
  72. return &grp;
  73. }
  74. UNLOCK;
  75. __set_errno(ret);
  76. return NULL;
  77. }