The Linux Programming Interface

(nextflipdebug5) #1
Login Accounting 823

The glibc implementation doesn’t perform this type of caching, but we should never-
theless employ this technique for the sake of portability.


Because the getutx*() functions return a pointer to a statically allocated struc-
ture, they are not reentrant. The GNU C library provides reentrant versions of
the traditional utmp functions (getutent_r(), getutid_r(), and getutline_r()), but
doesn’t provide reentrant versions of their utmpx counterparts. (SUSv3 doesn’t
specify the reentrant versions.)

By default, all of the getutx*() functions work on the standard utmp file. If we want to
use another file, such as the wtmp file, then we must first call utmpxname(), specifying
the desired pathname.


The utmpxname() function merely records a copy of the pathname given to it. It
doesn’t open the file, but does close any file previously opened by one of the other
calls. This means that utmpxname() doesn’t return an error if an invalid pathname is
specified. Instead, when one of the getutx*() functions is later called, it will return
an error (i.e., NULL, with errno set to ENOENT) when it fails to open the file.


Although not specified in SUSv3, most UNIX implementations provide
utmpxname() or the analogous utmpname() function.

Example program


The program in Listing 40-2 uses some of the functions described in this section to
dump the contents of a utmpx-format file. The following shell session log demon-
strates the results when we use this program to dump the contents of /var/run/utmp
(the default used by these functions if utmpxname() is not called):


$ ./dump_utmpx
user type PID line id host date/time
LOGIN LOGIN_PR 1761 tty1 1 Sat Oct 23 09:29:37 2010
LOGIN LOGIN_PR 1762 tty2 2 Sat Oct 23 09:29:37 2010
lynley USER_PR 10482 tty3 3 Sat Oct 23 10:19:43 2010
david USER_PR 9664 tty4 4 Sat Oct 23 10:07:50 2010
liz USER_PR 1985 tty5 5 Sat Oct 23 10:50:12 2010
mtk USER_PR 10111 pts/0 /0 Sat Oct 23 09:30:57 2010

For brevity, we edited out much of the output produced by the program. The lines
matching tty1 to tty5 are for logins on virtual consoles (/dev/tty[1-6]). The last line
of output is for an xterm session on a pseudoterminal.
The following output produced by dumping /var/log/wtmp shows that when a
user logs in and out, two records are written to the wtmp file. (We edited out all of


#define _GNU_SOURCE
#include <utmpx.h>

int utmpxname(const char *file);
Returns 0 on success, or –1 on error
Free download pdf