1 /* 2 * Copyright (c) 1980 Regents of the University of California. 3 * All rights reserved. The Berkeley software License Agreement 4 * specifies the terms and conditions for redistribution. 5 */ 6 7 #ifndef lint 8 char copyright[] = 9 "@(#) Copyright (c) 1980 Regents of the University of California.\n\ 10 All rights reserved.\n"; 11 #endif not lint 12 13 #ifndef lint 14 static char sccsid[] = "@(#)who.c 5.5 (Berkeley) 08/29/88"; 15 #endif not lint 16 17 /* 18 * who 19 */ 20 21 #include <stdio.h> 22 #include <utmp.h> 23 #include <pwd.h> 24 #include <ctype.h> 25 26 #define NMAX sizeof(utmp.ut_name) 27 #define LMAX sizeof(utmp.ut_line) 28 #define HMAX sizeof(utmp.ut_host) 29 30 struct utmp utmp; 31 struct passwd *pw; 32 struct passwd *getpwuid(); 33 34 char *ttyname(), *rindex(), *ctime(), *strcpy(); 35 36 main(argc, argv) 37 int argc; 38 char **argv; 39 { 40 register char *tp, *s; 41 register FILE *fi; 42 43 s = "/etc/utmp"; 44 if(argc == 2) 45 s = argv[1]; 46 if (argc == 3) { 47 tp = ttyname(0); 48 if (tp) 49 tp = rindex(tp, '/') + 1; 50 else { /* no tty - use best guess from passwd file */ 51 (void)strcpy(utmp.ut_line, "tty??"); 52 guess(); 53 exit(0); 54 } 55 } 56 if (!(fi = fopen(s, "r"))) { 57 fprintf(stderr, "who: cannot read %s.\n", s); 58 exit(1); 59 } 60 while (fread((char *)&utmp, sizeof(utmp), 1, fi) == 1) { 61 if (argc == 3) { 62 if (strcmp(utmp.ut_line, tp)) 63 continue; 64 if (!utmp.ut_name[0]) 65 guess(); 66 else 67 putline(); 68 exit(0); 69 } 70 if (utmp.ut_name[0] == '\0' && argc == 1) 71 continue; 72 putline(); 73 } 74 if (argc == 3) { 75 strncpy(utmp.ut_line, tp, sizeof(utmp.ut_line)); 76 guess(); 77 } 78 exit(0); 79 } 80 81 putline() 82 { 83 register char *cbuf; 84 85 printf("%-*.*s %-*.*s", 86 NMAX, NMAX, utmp.ut_name, 87 LMAX, LMAX, utmp.ut_line); 88 cbuf = ctime(&utmp.ut_time); 89 printf("%.12s", cbuf+4); 90 if (utmp.ut_host[0]) 91 printf("\t(%.*s)", HMAX, utmp.ut_host); 92 putchar('\n'); 93 } 94 95 guess() 96 { 97 pw = getpwuid(getuid()); 98 strncpy(utmp.ut_name, pw ? pw->pw_name : "?", NMAX); 99 time(&utmp.ut_time); 100 putline(); 101 } 102