如何以编程方式获取在Linux机器上登录的用户数? [英] How to programmatically get the number of users logged in on a linux machine?
问题描述
我想知道是否可以以编程方式获得使用C语言在Linux机器上登录的用户数量?我做了一些研究,发现了有关utmp.h的信息,但是由于并非所有程序都使用utmp日志记录,因此我认为它不够准确.在此先感谢任何愿意提供帮助的人.
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.
我对大家没有具体说明表示歉意,但是当我说登录用户时,我指的是任何通过shell登录的人.基本上,当您运行不带命令行参数的who命令时,您会得到什么.
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);
}
在与utmp玩了几天之后,我发现了.感谢您的帮助.
After a couple of days playing around with utmp, I figured it out. Thanks for the help guys.
这篇关于如何以编程方式获取在Linux机器上登录的用户数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!