I am running a C program in linux, which prints filename plus its user and group ownership. I am using getpwuid
and getgrgid
.
When file is owned by non-existent user (ie, there is no entry in /etc/passwd
for given UID on my machine), my program segfaults with "terminated by signal 11".
How can I make my program behave same as ls
, so that it prints numerical UID when user does not exist, instead of segfaulting?
Relevant code snippet is below:
lstat(filename,&fileStat)
struct group *grp;
struct passwd *pwd;
pwd = getpwuid(fileStat.st_uid);
printf(" %s", pwd->pw_name);
grp = getgrgid(fileStat.st_gid);
printf(" %s", grp->gr_name);