who.c (1440B)
1 /* see LICENSE file for copyright and license details */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <time.h> 7 #include <unistd.h> 8 9 #include "config.h" 10 #include "session.h" 11 #include "util.h" 12 13 static int mflag, lflag; 14 static char *tty; 15 16 static void 17 usage(void) 18 { 19 eprintf("usage: %s [-ml]\n", argv0); 20 } 21 22 static int 23 show(const struct SessionEntry *e, void *arg) 24 { 25 char timebuf[sizeof "yyyy-mm-dd hh:mm"]; 26 time_t t; 27 28 (void)arg; 29 if (!*e->user || !*e->line || e->line[0] == '~') 30 return 0; 31 if (mflag != 0 && strcmp(e->line, tty) != 0) 32 return 0; 33 if (!!strcmp(e->user, "LOGIN") == lflag) 34 return 0; 35 t = e->time; 36 strftime(timebuf, sizeof timebuf, "%Y-%m-%d %H:%M", localtime(&t)); 37 printf("%-8s %-12s %-16s\n", e->user, e->line, timebuf); 38 return 0; 39 } 40 41 // ?man who: show logged in users 42 // ?man display a list of users currently logged into the system 43 int 44 main(int argc, char *argv[]) 45 { 46 char *ttmp; 47 48 ARGBEGIN 49 { 50 // ?man -m: specify mode or limit 51 case 'm': 52 mflag = 1; 53 tty = ttyname(0); 54 if (!tty) 55 eprintf("ttyname: stdin:"); 56 if ((ttmp = strrchr(tty, '/'))) 57 tty = ttmp + 1; 58 break; 59 // ?man -l: list in long format 60 case 'l': 61 lflag = 1; 62 break; 63 default: 64 usage(); 65 } 66 ARGEND; 67 68 if (argc > 0) 69 usage(); 70 71 if (session_each(UTMP_PATH, show, NULL) < 0) 72 eprintf("fopen: %s:", UTMP_PATH); 73 return 0; 74 }