21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The function used to look up user information by name has the following signature:<br />

#include <br />

#include <br />

struct passwd *getpwnam(const char *name);<br />

Both functions return a pointer to a structure allocated internally by the runtime<br />

library. One side effect of this behavior is that successive calls replace the information<br />

from the previous call. Another is that the functions are not thread-safe. If either<br />

function fails to find the requested user information, a NULL pointer is returned.<br />

The contents of the passwd structure differ across platforms, but some fields remain<br />

the same everywhere. Of particular interest to us in this recipe are the two fields pw_<br />

name and pw_uid. These two fields are what enable mapping between names and<br />

numeric identifiers. For example, the following two functions will obtain mappings:<br />

#include <br />

#include <br />

#include <br />

int spc_user_getname(uid_t uid, char **name) {<br />

struct passwd *pw;<br />

if (!(pw = getpwuid(uid)) ) {<br />

endpwent( );<br />

return -1;<br />

}<br />

*name = strdup(pw->pw_name);<br />

endpwent( );<br />

return 0;<br />

}<br />

int spc_user_getuid(char *name, uid_t *uid) {<br />

struct passwd *pw;<br />

if (!(pw = getpwnam(name))) {<br />

endpwent( );<br />

return -1;<br />

}<br />

*uid = pw->pw_uid;<br />

endpwent( );<br />

return 0;<br />

}<br />

Note that spc_user_getname( ) will dynamically allocate a buffer to return the user’s<br />

name, which must be freed by the caller. Also notice the use of the function<br />

endpwent( ). This function frees any resources allocated by the lookup functions. Its<br />

use is important because failure to free the resources can cause unexpected leaking of<br />

memory, file descriptors, socket descriptors, and so on. Exactly what types of<br />

resources may be leaked vary depending on the underlying implementation, which<br />

may differ not only from platform to platform, but also from installation to installation.<br />

Getting User and Group Information on Unix | 373<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!