tags:

views:

49

answers:

1

Following is the final code I was working on. I can sleep and show again other messages with sleep() but I can't print what I originally wanted which is inside 2nd while loop. As far as I tested, while((ptr=getutent()) != NULL) would be the problem but I don't know how to solve. I would really appreciate if anyone can help me. Thanks

Note: The program is showing current login user for every 5 seconds until user stop with Ctrl+c.

#include <utmp.h>
#include <pwd.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(void)
{
    struct utmp *ptr;
    struct passwd *pwd;

    while(1)
    {

        while((ptr=getutent()) != NULL)
        {
            if(ptr->ut_type==USER_PROCESS)
            {
                pwd=getpwnam(ptr->ut_user);      
                printf("USERNAME = %s | ID = %d | GID = %d | ",p
tr->ut_user,pwd->pw_uid,pwd->pw_gid);
                printf("HomeDir = %s | HOST = %s\n",pwd->pw_dir,
ptr->ut_host);
            }
        }

        sleep(3);
        fflush(stdout);
    }

}
+2  A: 

You want to use setutent() to set the file pointer back to the beginning of the utmp file.

Richard Pennington
Oh I see. Let me try with setutent()
Devyn
Oh you are professional! Thank you so much. That's what I want!
Devyn
And use `endutent()` when you are done to release the file descriptor used by the family of functions. There's a pattern with these things, too: [getpwent(), setpwent(), endpwent()], [getgrent(), setgrent(), endgrent()], and [getutent(), setutent(), endutent()]. to name but three sets of such functions.
Jonathan Leffler
Others similar families of functions: `getaliasent`, `getfsent`, `gethostent`, `getmntent`, `getnetent`, `getnetgrent`, `getprotoent`, `getrpcent`, `getservent`, `getspent`, `getttyent`, `getutxent`.
ephemient
I hope Devyn also learns the value of man, as in "man getutent". It can be very useful.
Richard Pennington
Hey Richard, I tried "man getutent" but I just got "no manual for it". I'm using MacOSX.
Devyn