getgrgid.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * getgrgid.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. #include <sys/types.h>
  23. #include <unistd.h>
  24. #include <fcntl.h>
  25. #include <paths.h>
  26. #include <errno.h>
  27. #include "config.h"
  28. #ifdef __UCLIBC_HAS_THREADS__
  29. #include <pthread.h>
  30. static pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
  31. # define LOCK pthread_mutex_lock(&mylock)
  32. # define UNLOCK pthread_mutex_unlock(&mylock);
  33. #else
  34. # define LOCK
  35. # define UNLOCK
  36. #endif
  37. /* Search for an entry with a matching group ID. */
  38. int getgrgid_r (gid_t gid, struct group *group, char *buffer,
  39. size_t buflen, struct group **result)
  40. {
  41. int grp_fd;
  42. if ((grp_fd = open(_PATH_GROUP, O_RDONLY)) < 0)
  43. return errno;
  44. *result = NULL;
  45. while (__getgrent_r(group, buffer, buflen, grp_fd) == 0) {
  46. if (group->gr_gid == gid) {
  47. close(grp_fd);
  48. *result = group;
  49. return 0;
  50. }
  51. }
  52. close(grp_fd);
  53. return EINVAL;
  54. }
  55. struct group *getgrgid(const gid_t gid)
  56. {
  57. int ret;
  58. struct group *result;
  59. static struct group grp;
  60. static char line_buff[GRP_BUFFER_SIZE];
  61. LOCK;
  62. if ((ret=getgrgid_r(gid, &grp, line_buff, sizeof(line_buff), &result)) == 0) {
  63. UNLOCK;
  64. return &grp;
  65. }
  66. UNLOCK;
  67. __set_errno(ret);
  68. return NULL;
  69. }