ubase

suckless linux base utils
git clone git://git.2f30.org/ubase
Log | Files | Refs | README | LICENSE

who.c (1212B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <string.h>
      5 #include <time.h>
      6 #include <unistd.h>
      7 #include <utmp.h>
      8 
      9 #include "config.h"
     10 #include "util.h"
     11 
     12 static void
     13 usage(void)
     14 {
     15 	eprintf("usage: %s [-ml]\n", argv0);
     16 }
     17 
     18 int
     19 main(int argc, char *argv[])
     20 {
     21 	struct utmp usr;
     22 	FILE *ufp;
     23 	char timebuf[sizeof "yyyy-mm-dd hh:mm"];
     24 	char *tty, *ttmp;
     25 	int mflag = 0, lflag = 0;
     26 	time_t t;
     27 
     28 	ARGBEGIN {
     29 	case 'm':
     30 		mflag = 1;
     31 		tty = ttyname(0);
     32 		if (!tty)
     33 			eprintf("ttyname: stdin:");
     34 		if ((ttmp = strrchr(tty, '/')))
     35 			tty = ttmp+1;
     36 		break;
     37 	case 'l':
     38 		lflag = 1;
     39 		break;
     40 	default:
     41 		usage();
     42 	} ARGEND;
     43 
     44 	if (argc > 0)
     45 		usage();
     46 
     47 	if (!(ufp = fopen(UTMP_PATH, "r")))
     48 		eprintf("fopen: %s:", UTMP_PATH);
     49 
     50 	while (fread(&usr, sizeof(usr), 1, ufp) == 1) {
     51 		if (!*usr.ut_name || !*usr.ut_line ||
     52 		    usr.ut_line[0] == '~')
     53 			continue;
     54 		if (mflag != 0 && strcmp(usr.ut_line, tty) != 0)
     55 			continue;
     56 		if (!!strcmp(usr.ut_name, "LOGIN") == lflag)
     57 			continue;
     58 		t = usr.ut_time;
     59 		strftime(timebuf, sizeof timebuf, "%Y-%m-%d %H:%M", localtime(&t));
     60 		printf("%-8s %-12s %-16s\n", usr.ut_name, usr.ut_line, timebuf);
     61 	}
     62 	fclose(ufp);
     63 	return 0;
     64 }