doc: use semicolon instead of period in option descriptions
[coreutils.git] / src / group-list.c
blob7d4995b5c07a5f152f4facb5d3fddce8fea0ec6b
1 /* group-list.c --Print a list of group IDs or names.
2 Copyright (C) 1989-2013 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Arnold Robbins.
18 Major rewrite by David MacKenzie, djm@gnu.ai.mit.edu.
19 Extracted from id.c by James Youngman. */
21 #include <config.h>
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <pwd.h>
25 #include <grp.h>
27 #include "system.h"
28 #include "error.h"
29 #include "mgetgroups.h"
30 #include "quote.h"
31 #include "group-list.h"
34 /* Print all of the distinct groups the user is in. */
35 extern bool
36 print_group_list (const char *username,
37 uid_t ruid, gid_t rgid, gid_t egid,
38 bool use_names)
40 bool ok = true;
41 struct passwd *pwd = NULL;
43 if (username)
45 pwd = getpwuid (ruid);
46 if (pwd == NULL)
47 ok = false;
50 if (!print_group (rgid, use_names))
51 ok = false;
53 if (egid != rgid)
55 putchar (' ');
56 if (!print_group (egid, use_names))
57 ok = false;
61 gid_t *groups;
62 int i;
64 int n_groups = xgetgroups (username, (pwd ? pwd->pw_gid : egid), &groups);
65 if (n_groups < 0)
67 if (username)
69 error (0, errno, _("failed to get groups for user %s"),
70 quote (username));
72 else
74 error (0, errno, _("failed to get groups for the current process"));
76 return false;
79 for (i = 0; i < n_groups; i++)
80 if (groups[i] != rgid && groups[i] != egid)
82 putchar (' ');
83 if (!print_group (groups[i], use_names))
84 ok = false;
86 free (groups);
88 return ok;
91 /* Convert a gid_t to string. Do not use this function directly.
92 Instead, use it via the gidtostr macro.
93 Beware that it returns a pointer to static storage. */
94 static char *
95 gidtostr_ptr (gid_t const *gid)
97 static char buf[INT_BUFSIZE_BOUND (uintmax_t)];
98 return umaxtostr (*gid, buf);
100 #define gidtostr(g) gidtostr_ptr (&(g))
102 /* Print the name or value of group ID GID. */
103 extern bool
104 print_group (gid_t gid, bool use_name)
106 struct group *grp = NULL;
107 bool ok = true;
109 if (use_name)
111 grp = getgrgid (gid);
112 if (grp == NULL)
114 error (0, 0, _("cannot find name for group ID %lu"),
115 (unsigned long int) gid);
116 ok = false;
120 char *s = grp ? grp->gr_name : gidtostr (gid);
121 fputs (s, stdout);
122 return ok;