gtpc2m3zC/C++ Language Support User's Guide

getpwuid-Access the User Database by User ID

This function gets information about the user with the specified uid.

Format

#include <pwd.h>
struct passwd *getpwuid(uid_t uid)

uid
A UID value representing the user ID to be retrieved from file.

Normal Return

If successful, the getpwuid function returns a pointer to struct passwd containing an entry from the user database for the specified uid. The return value is a pointer to static data that is overwritten by each call.

struct passwd, defined in the pwd.h C header file, contains the following members:

pw_name
Pointer to the password user name character string.

pw_uid
The numeric user ID (UID).

pw_gid
The numeric group ID (GID).

pw_gecos
Pointer to the comment character string.

pw_dir
Pointer to the initial working directory character string.

pw_shell
Pointer to the character string name of the initial shell (user program).

Error Return

If unsuccessful, the getpwuid function returns a NULL pointer and sets errno to one of the following:

EIO
An input/output (I/O) error occurred.

EMFILE
The process has already reached its maximum number of open file descriptors. This limit is given by OPEN_MAX, which is defined in the limits.h header file.

ENFILE
The TPF system has already reached its maximum number of open files.

Programming Considerations

Examples

The following example shows accessing the database for user ID 0.

#include <pwd.h>
#include <stdio.h>
 
int main(void) {
 
char prthdr[] =
             "getpwuid() returned the following info for your user id:"
struct passwd *p;
uid_t uid = 0;
 
if ( ( p = getpwuid ( uid ) ) == NULL )
 
     perror ( "getpwuid() error" );
  else {
       printf( "%s\n", prthdr );
       printf( "  pw_name  :  %s\n", p->pw_name );
       printf( "  pw_uid   :  %d\n", (int) p->pw_uid  );
       printf( "  pw_gid   :  %d\n", (int) p->pw_gid  );
       printf( "  pw_dir   :  %s\n", p->pw_dir  );
       printf( "  pw_shell :  %s\n", p->pw_shell);
  }
  return 0;
}

The getpwuid function returns the following information for the user ID of the calling function.

getpwuid() returned the following info for your user id:
pwname   :  root
pw_uid   :  0
pw_gid   :  0
pw_dir   :  /
pw_shell :

Related Information

getuid-Get the Real User ID.