modern syntax for asgops and inits; sccs keywords
[unix-history] / usr / src / usr.bin / who / who.c
CommitLineData
51df51c9
DF
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
b899e9ac 7#ifndef lint
51df51c9
DF
8char 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
90b37ef8 14static char sccsid[] = "@(#)who.c 5.2 (Berkeley) %G%";
51df51c9
DF
15#endif not lint
16
aba4c79c
BJ
17/*
18 * who
19 */
20
90b37ef8 21#include <sys/param.h>
aba4c79c
BJ
22#include <utmp.h>
23#include <pwd.h>
90b37ef8
KB
24#include <stdio.h>
25#include <strings.h>
751509f1 26#include <ctype.h>
aba4c79c 27
90b37ef8
KB
28#define NMAX sizeof(utmp.ut_name)
29#define LMAX sizeof(utmp.ut_line)
30#define HMAX sizeof(utmp.ut_host)
aba4c79c 31
90b37ef8 32static struct utmp utmp; /* read buffer */
cf288731 33
90b37ef8
KB
34main(argc,argv)
35int argc;
36char **argv;
aba4c79c 37{
90b37ef8
KB
38 register FILE *fp; /* utmp file pointer */
39 register char *tp, /* tty name */
40 *fname; /* utmp file name */
41 struct passwd *pw, /* user passwd structure */
42 *getpwuid();
43 char hostname[MAXHOSTNAMELEN], /* host name */
44 *ttyname();
45 uid_t getuid();
46 long time();
aba4c79c 47
90b37ef8
KB
48 switch(argc) {
49 case 2:
50 fname = argv[1];
51 break;
52 case 3:
53 if (!(tp = ttyname(0))) {
54 /*
55 * no tty -- use best guess from passwd file.
56 * next line is a kludge, but as of now getuid
57 * returns a "uid_t" and getpwuid takes an int.
58 */
59 pw = getpwuid((int)getuid());
60 strncpy(utmp.ut_name,pw ? pw->pw_name : "?",NMAX);
61 strcpy(utmp.ut_line,"tty??");
62 time(&utmp.ut_time);
63 putline();
64 exit(0);
65 }
66 tp = rindex(tp,'/') + 1;
67 if (gethostname(hostname,sizeof(hostname)) == -1) {
68 perror("gethostname");
69 exit(1);
70 }
71 case 1:
72 fname = "/etc/utmp";
73 break;
74 default:
75 fputs("usage: who [ utmp_file ]\nor who am i\n",stderr);
76 exit(1);
aba4c79c 77 }
90b37ef8
KB
78 if (!(fp = fopen(fname,"r"))) {
79 perror(fname);
aba4c79c
BJ
80 exit(1);
81 }
90b37ef8 82 while (fread((char *)&utmp,sizeof(utmp),1,fp) == 1)
b899e9ac 83 if (argc == 3) {
90b37ef8
KB
84 if (!strcmp(utmp.ut_line,tp)) {
85 printf("%s!",hostname);
86 putline();
87 exit(0);
88 }
aba4c79c 89 }
90b37ef8
KB
90 else if (argc != 1 || *utmp.ut_name)
91 putline();
aba4c79c
BJ
92}
93
94putline()
95{
90b37ef8
KB
96 register char *cbuf;
97 char *ctime();
aba4c79c 98
90b37ef8
KB
99 cbuf = ctime(&utmp.ut_time) + 4;
100 printf("%-*.*s %-*.*s%.12s",NMAX,NMAX,utmp.ut_name,LMAX,LMAX,utmp.ut_line,cbuf);
101 if (*utmp.ut_host)
102 printf("\t(%.*s)",HMAX,utmp.ut_host);
b899e9ac 103 putchar('\n');
aba4c79c 104}