On Mon, May 6, 2013 at 6:06 PM, Friedrich Locke <[email protected]> wrote: > I am in need to write a simple program to return the passwd entry for a > given uid number. > > Here you have it: > > #include <sys/types.h> > #include <errno.h> > #include <pwd.h> > #include <stdio.h> > > int > main(int argc, char **argv) > { > struct passwd *p; > int e; > > e = errno, errno = 0; > p = getpwuid(0); > if (errno) {
This isn't right. To test for whether getpwuid() found an entry for the UID, test whether its return value is not NULL. If it found the UID it'll return non-NULL. If it didn't find the UID but didn't hit any error (it could read the passwd file, etc), then it will return NULL and not change errno. Only if it didn't find it because of an error will it set errno. (...or at least that's the theory: if you find a case where it sets errno but succeeds, returning non-NULL, please provide details about your config, perhaps a ktrace of the program, so that we can track down the problem.) Note that in the "no errors, but didn't find it" case, your program would segfault when it tried to dereference the NULL pointer here: ... > fprintf(stdout, "%s\n", p->pw_name); > return 0; > } > > > When i execute it i get this on a openbsd: > > sioux@lion$ ./pw > errno is: 13 > sioux@lion$ > > Any ideia why openbsd implementation of getpwuid returns error ? 13 == EACCES. Are you running this as a user who can't read /etc/pwd.db ? Philip Guenther

