lazysphere/src/commands/id.c

42 lines
975 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(user_id) {
2023-04-28 04:39:56 +00:00
uid_t uid = getuid();
gid_t gid = getgid();
2023-04-27 23:41:32 +00:00
struct passwd* pw = getpwuid(uid);
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
}
int ngroups = 0;
getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups);
2023-04-28 04:39:56 +00:00
gid_t groups[ngroups];
2023-04-27 23:41:32 +00:00
getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
struct group* ugr = getgrgid(gid);
printf("uid=%d(%s) gid=%d(%s) ",
uid, ugr->gr_name, gid, ugr->gr_name);
if (ngroups > 0) {
printf("groups=");
}
for (int i = 0; i < ngroups; i++){
struct group* gr = getgrgid(groups[i]);
if(gr == 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
}
printf("%d(%s)", gr->gr_gid, gr->gr_name);
if (i + 1 < ngroups) putchar(',');
}
printf("\b\n");
return EXIT_SUCCESS;
}