lazysphere/src/commands/groups.c

43 lines
816 B
C
Raw Normal View History

2023-04-27 23:41:32 +00:00
#include "../command.h"
#include <grp.h>
#include <pwd.h>
COMMAND_EMPTY(groups) {
2023-05-04 20:10:37 +00:00
uid_t uid;
int ngroups, i;
gid_t* groups;
struct passwd* pw;
uid = getuid();
2023-04-27 23:41:32 +00:00
2023-05-04 20:10:37 +00:00
pw = getpwuid(uid);
2023-04-27 23:41:32 +00:00
if(pw == NULL){
2023-05-03 16:17:56 +00:00
error("failed to fetch groups: %s", strerror(errno));
2023-04-27 23:41:32 +00:00
}
2023-05-04 20:10:37 +00:00
ngroups = 0;
2023-04-27 23:41:32 +00:00
getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups);
2023-05-04 20:10:37 +00:00
groups = malloc(sizeof(gid_t) * ngroups);
2023-04-27 23:41:32 +00:00
getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
2023-05-04 20:10:37 +00:00
for (i = 0; i < ngroups; i++){
2023-04-27 23:41:32 +00:00
struct group* gr = getgrgid(groups[i]);
2023-05-04 20:10:37 +00:00
if(gr == NULL) {
free(groups);
2023-05-03 16:17:56 +00:00
error("failed to fetch groups: %s", strerror(errno));
2023-04-27 23:41:32 +00:00
}
2023-05-04 20:10:37 +00:00
2023-04-27 23:41:32 +00:00
printf("%s ",gr->gr_name);
}
2023-05-04 20:10:37 +00:00
2023-04-27 23:41:32 +00:00
printf("\n");
2023-05-04 20:10:37 +00:00
free(groups);
2023-04-27 23:41:32 +00:00
return EXIT_SUCCESS;
}