These functions operate on the password database which is described in
passwd(5). Each entry in the database is defined by the structure
passwd found in the include file
<pwd.h>:
struct passwd {
char *pw_name; /* user name */
char *pw_passwd; /* encrypted password */
uid_t pw_uid; /* user uid */
gid_t pw_gid; /* user gid */
time_t pw_change; /* password change time */
char *pw_class; /* user login class */
char *pw_gecos; /* general information */
char *pw_dir; /* home directory */
char *pw_shell; /* default shell */
time_t pw_expire; /* account expiration */
};
The functions
getpwnam() and
getpwuid() search the password database for the given user name pointed to by
name or user id pointed to by
uid respectively, always returning the first one encountered. Identical user names or user ids may result in undefined behavior.
The
getpwent() function sequentially reads the password database and is intended for programs that wish to process the complete list of users.
The functions
getpwnam_r(),
getpwuid_r(), and
getpwent_r() act like their non re-entrant counterparts, updating the contents of
pw and storing a pointer to that in
result, and returning
0. Storage used by
pw is allocated from
buffer, which is
buflen bytes in size. If the requested entry cannot be found,
result will point to
NULL and
0 will be returned. If an error occurs, a non-zero error number will be returned and
result will point to
NULL. Calling
getpwent_r() from multiple threads will result in each thread reading a disjoint portion of the password database.
The
setpassent() function accomplishes two purposes. First, it causes
getpwent() to “rewind” to the beginning of the database. Additionally, if
stayopen is non-zero, file descriptors are left open, significantly speeding up subsequent accesses for all of the functions. (This latter functionality is unnecessary for
getpwent() as it doesn't close its file descriptors by default.)
It is dangerous for long-running programs to keep the file descriptors open as the database will become out of date if it is updated while the program is running.
The
setpwent() function is equivalent to
setpassent() with an argument of zero.
The
endpwent() function closes any open files.
These functions have been written to “shadow” the password file, e.g. allow only certain programs to have access to the encrypted password. If the process which calls them has an effective uid of 0, the encrypted password will be returned, otherwise, the password field of the returned structure will point to the string ‘*'.