Ishit Mehta
Ishit Mehta

Reputation: 119

How to find the owner and group name from uid and gid using system calls listed in man 2 pages?

I have an assignment in which I have to simulate ls -l unix command using C. I have figured out everything except finding the owner and the group of a particular file. I have the uid and gid from the stat structure using stat() system call, but I am not able to map them to the actual name of the user and owner respectively. I am supposed to use only those system calls which are listed in the man 2 pages. I have tried searching for an answer, but everywhere it says to use getpwnam() call, which I can't as it is not listed in the man 2 pages.

Upvotes: 0

Views: 1999

Answers (3)

sjnarv
sjnarv

Reputation: 2374

Yes, getpwnam(3) and getgrnam(3) are the ways you'd do this in settings not restricted to system calls only.

But even reading the contents of /etc/passwd using only system calls poses a challenge or two. Regular friends like fopen(3), fread(3) and fgets(3) aren't available, nor are string helpers like strsep(3). I guess you're stuck with read(2). You can read one character at a time using read(2), and do a crude parse of contents that way.

Or you could set up a character array that's big enough to read all of /etc/passwd into memory, and walk over the file contents that way. You'll have info stat(2) returned to tell how big /etc/passwd is, so could either fail if it's too big for your assumptions, or implement a buffering strategy yourself.

Or you could look into sbrk(2), and be sure you've enough memory to land all of /etc/passwd in memory from one read(2).

However you read the contents, you'll have some conversion to do of text -- strings of digits -- to C numeric types, harder when atoi(3) isn't available.

Also fun: converting time_t (time(2) output; also some of the fields of struct stat) to a nice string:

1409264099 -> Thu Aug 28 17:14:59 2014

Are these really the rules of the assignment...? C is crude enough without the presence of a conventional libc...

Upvotes: 2

countermode
countermode

Reputation: 322

Only system calls... oh dear!

Well, I would mmap /etc/passwd and /etc/group and search the memory regions using basic C operations. Both files are line oriented, so lines are separated by \n, and within each line the entries are separated by colons.

Upvotes: 0

David Williams
David Williams

Reputation: 21

You can search the /etc/passwd file for what you require. You can find out the structure of the /etc/passwd file with man 5 passwd. There is no system call that will do this for you.

Upvotes: 0

Related Questions