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.
#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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With