getgroups.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Print out the gids of all groups for the current user. This is like
  3. * `id -G` on Linux, but it's too hard to find a portable equivalent.
  4. *
  5. * Copyright (C) 2002 Martin Pool
  6. * Copyright (C) 2003-2008 Wayne Davison
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License version 3 as
  10. * published by the Free Software Foundation.
  11. *
  12. * This program 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
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License along
  18. * with this program; if not, visit the http://fsf.org website.
  19. */
  20. #include "rsync.h"
  21. int
  22. main(UNUSED(int argc), UNUSED(char *argv[]))
  23. {
  24. int n, i;
  25. gid_t *list;
  26. gid_t gid = MY_GID();
  27. int gid_in_list = 0;
  28. #ifdef HAVE_GETGROUPS
  29. if ((n = getgroups(0, NULL)) < 0) {
  30. perror("getgroups");
  31. return 1;
  32. }
  33. #else
  34. n = 0;
  35. #endif
  36. list = (gid_t*)malloc(sizeof (gid_t) * (n + 1));
  37. if (!list) {
  38. fprintf(stderr, "out of memory!\n");
  39. exit(1);
  40. }
  41. #ifdef HAVE_GETGROUPS
  42. if (n > 0)
  43. n = getgroups(n, list);
  44. #endif
  45. for (i = 0; i < n; i++) {
  46. printf("%lu ", (unsigned long)list[i]);
  47. if (list[i] == gid)
  48. gid_in_list = 1;
  49. }
  50. /* The default gid might not be in the list on some systems. */
  51. if (!gid_in_list)
  52. printf("%lu", (unsigned long)gid);
  53. printf("\n");
  54. return 0;
  55. }