23,121
社区成员
发帖
与我相关
我的任务
分享
1 /*who2.c - a second version of the who program
2 * open ,read utmp file , and show results
3 */
4 #include <stdio.h>
5 #include <utmp.h>
6 #include <unistd.h>
7 #include <fcntl.h>
8 #include <time.h>
9 #define SHOWHOST
10
11 int main()
12 {
13 void show_info(struct utmp * utbufp );
14 void _showtime(long);
15 struct utmp current_record;
16 int utmpfd;
17 int reclen = sizeof ( current_record );
18 if (( utmpfd = open ( UTMP_FILE , O_RDONLY ) ) == -1 ) /* int fd = open ( char * name , int how ) */
19 {
20 perror( UTMP_FILE );
21 exit(1);
22 }
23 while ( read (utmpfd , ¤t_record, reclen ) == reclen ) /*ssize_t read(int fd, void *buf, size_t count);8*/
24 show_info( ¤t_record );
25 close( utmpfd );
26 return 0;
27 }
28
29 /*show info ()
30 * displays contexts of the utmp struct in human readdable form
31 * NOTE these sizes should not be hardwired
32 */
33
34 void show_info(struct utmp * utbufp )
35 {
36 if( utbufp->ut_type != USER_PROCESS)
37 return ;
38 printf( " %-8.8s " ,utbufp->ut_user );
39 printf( " " );
40 printf( " %-8.8s " ,utbufp->ut_line );
41 printf( " " );
42 showtime(utbufp->ut_time );
43 printf( " " );
44
45 #ifdef SHOWHOST
46 if ( utbufp->ut_user[0] != '\0' )
47 printf( " (%s)" ,utbufp->ut_host );
48 #endif
49 printf(" \n " );
50 }
51
52
53 void showtime(long timeval )
54 /* displays time in a format fit for human consumption
55 * use ctime to build a string then picks parts out of it
56 * Note : % 12,12s prints a string 12 chars wide and LIMITS
57 * it to 12chars
58 */
59 {
60 char *cp ;
61 cp = ctime ( &timeval ) ; /* char *ctime(const time_t *clock);**/
62 printf(" %12.12s" , cp +4 );
63 }
64
65
struct utmp {
short ut_type; /* type of login */
pid_t ut_pid; /* pid of login process */
char ut_line[UT_LINESIZE]; /* device name of tty - "/dev/" */
char ut_id[4]; /* init id or abbrev. ttyname */
char ut_user[UT_NAMESIZE]; /* user name */
char ut_host[UT_HOSTSIZE]; /* hostname for remote login */
struct exit_status ut_exit; /* The exit status of a process
marked as DEAD_PROCESS. */
long ut_session; /* session ID, used for windowing*/
struct timeval ut_tv; /* time entry was made. */
int32_t ut_addr_v6[4]; /* IP address of remote host. */
char pad[20]; /* Reserved for future use. */
};
/* Backwards compatibility hacks. */
#define ut_name ut_user
#ifndef _NO_UT_TIME
#define ut_time ut_tv.tv_sec
#endif
#define ut_xtime ut_tv.tv_sec
#define ut_addr ut_addr_v6[0]