User Tools

Site Tools


user:jbrant:systems:who2
/*who2.c - a first version of the who program
 *           open read UTMP file, and show results
 */
#include    <stdio.h>
#include    <stdlib.h>
#include    <utmp.h>
#include    <fcntl.h>
#include    <unistd.h>
#include    <time.h>

#define SHOWHOST    /* include remote machine on output */
void showtime(long);
void show_info(struct utmp *);

int main()
{
        struct utmp  utbuf ; /* read info into here */
        int           utmpfd;  /* read from this discriptor */

        if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1)
        {
                perror( UTMP_FILE );    /* UTMP_FILE is in  utmp.h */
                exit(1);
        }
        while (read(utmpfd, &utbuf, sizeof(utbuf)) == sizeof(utbuf))
                show_info( &utbuf );
        close(utmpfd);
        return 0;      /* went ok */
}

/*
 * show info()
 *      displays contents of the utmp struct in human readable form
 */
void show_info( struct utmp *utbufp )
{
        if ( utbufp -> ut_type != USER_PROCESS )
                return;

        printf("%-8.8s", utbufp->ut_name);
        printf(" ");
        printf("%-8.8s", utbufp->ut_line);
        printf(" ");
        printf("%10ld", utbufp->ut_time);
        printf(" ");

#ifdef SHOWHOST
        if (utbufp->ut_host[0] != '\0' )
                printf(" (%s) ", utbufp->ut_host);/* the host */

#endif
        printf("\n");
}

void showtime( long timeval )
/*
 * displays time in a format fit for human consumption
 * uses ctime to build a string then picks parts out of it
 * Note: %12.12s prints a string 12 chars wide and LIMITS
 * it to 12chars.
 */
{
        char *cp;                /*  to hold address of time   */
        cp = ctime(&timeval);    /*  convert time to sting     */




        printf("%12.12s", cp+4 ); /* pick 12  chars form pos 4 */
}
user/jbrant/systems/who2.txt · Last modified: 2010/11/29 10:49 by jbrant