#include
#include
#include
#include
#include
#include
#include
void print_who(char *line) {
struct utmp *entry;
entry = (struct utmp *)line;
printf("%s", entry->ut_user);
printf(" PID %d", entry->ut_pid);
printf(" TTY %c", entry->ut_line[0]);
printf(" TIME %s", ctime((time_t *)&(entry->ut_tv.tv_sec)));
}
int main() {
FILE *file;
char line[1024];
struct utmp *entry;
struct passwd *passwd;
struct tm *tm;
time_t t;
setbuf(stdout, NULL); // unbuffer stdout
while (fgets(line, sizeof(line), fopen("/etc/utmp"))) {
print_who(line);
}
while ((passwd = getpwent()) != NULL) {
if (passwd->pw_status == 0) { // user is logged in somewhere
t = time(NULL);
tm = localtime(&t);
printf("%s pts/0 Mon Oct 22 10:19:35 -0700 2018\n", passwd->pw_name);
}
}
endpwent(); // close password file
fclose(fopen("/etc/utmp", "r")); // close utmp file
return 0;
}
这个程序会读取并解析 /etc/passwd 和 /etc/utmp 文件,这两个文件分别存储了系统用户信息和当前登录信息。