Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically get the number of users logged in on a linux machine?

Tags:

c

linux

bash

I was wondering if it was possible to programmatically get the number of users logged in on a Linux machine in C? I did some researching and found out about utmp.h but since not all programs use utmp logging, I did not think it would be accurate enough. Thanks in advance to anyone willing to help.

EDIT: I apologize guys for not being more specific but when I say logged in users, I am referring to any logged in via shell. Basically what you get when you run the who command with no command line arguments.

like image 292
Error1f1f Avatar asked Jan 22 '23 01:01

Error1f1f


1 Answers

#include <utmp.h>
#include <err.h>

#define NAME_WIDTH  8

    FILE *ufp;
    int numberOfUsers = 0;
    struct utmp usr;
    ufp = file(_PATH_UTMP);
    while (fread((char *)&usr, sizeof(usr), 1, ufp) == 1) {
    if (*usr.ut_name && *usr.ut_line && *usr.ut_line != '~') {
         numberOfUsers++;
        }
    }

    FILE *file(char *name)
    {
        FILE *ufp;

        if (!(ufp = fopen(name, "r"))) {
            err(1, "%s", name);
        }
        return(ufp);
    }

After a couple of days playing around with utmp, I figured it out. Thanks for the help guys.

like image 161
Error1f1f Avatar answered Jan 29 '23 15:01

Error1f1f