linux下での簡易whoコマンドの実装
3566 ワード
/*
who , 、 、
*/
#include <stdio.h>
#include <utmp.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char* argv[])
{
int fp;
struct tm *temp;
struct utmp buf;
time_t t1;
char buf1[50];
int n = sizeof(struct utmp);
// UTMP_FILE , /var/run/utmp
fp = open(UTMP_FILE, O_RDONLY);
//fp = open("/var/run/utmp", O_RDONLY);
if (fp == -1) {
perror("/var/run/umtp");
exit(1);
}
while (read(fp, &buf, n) == n)
if (buf.ut_type == 7) {
// time_t
t1 = buf.ut_tv.tv_sec;
//
temp = localtime(&t1);
strftime(buf1, 50, "%F %R", temp);
printf("%s\t%s\t%s
", buf.ut_user, buf.ut_line, buf1);
//printf("%s\t%s\t%s", buf.ut_user, buf.ut_line, ctime(&t1));
}
close(fp);
}
/*
,read_record ,
*/
#include <stdio.h>
#include <utmp.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#define NUM 16
int read_record(int fp, char* buf, int num)
{
int n;
n = read(fp, buf, num*sizeof(struct utmp));
return n/sizeof(struct utmp);
}
int main(int argc, char* argv[])
{
int fp;
struct tm *temp;
struct utmp *buf;
time_t t1;
char buf2[NUM*sizeof(struct utmp)];
char buf1[50];
int count, current;
int n = sizeof(struct utmp);
fp = open(UTMP_FILE, O_RDONLY);
if (fp == -1) {
perror("/var/run/umtp");
exit(1);
}
while ((count =read_record(fp, buf2, NUM)) != 0) {
current = 0;
while (count--) {
buf = (struct utmp*)buf2+current*sizeof(struct utmp);
if (buf->ut_type == 7) {
t1 = buf->ut_tv.tv_sec;
temp = localtime(&t1);
strftime(buf1, 50, "%F %R", temp);
printf("%s\t%s\t%s
", buf->ut_user, buf->ut_line, buf1);
}
current++;
}
}
close(fp);
}
/*
, utmp
logout username
*/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <utmp.h>
#include <time.h>
int main(int argc, char* argv[])
{
int fd;
struct utmp buf;
int n;
n = sizeof(struct utmp);
if (argc == 1) {
fprintf(stderr, "logout:missing file operand");
exit(1);
}
fd = open("utmp", O_RDWR);
if (fd == -1) {
perror("open failed");
exit(1);
}
while (read(fd, &buf, n) == n)
if (buf.ut_type == 7 && (!strcmp(buf.ut_line, argv[1]))) {
buf.ut_type = DEAD_PROCESS;
if (time(&buf.ut_time) == -1) {
perror("time update");
exit(1);
}
if (lseek(fd, -n, SEEK_CUR) == -1) {
perror("lseek error");
exit(1);
}
if (write(fd, &buf, n) != n) {
perror("write error");
exit(1);
}
break;
}
close(fd);
return 0;
}
まとめ:
時間処理関数、localtimeとgtime、localtimeはタイムゾーンを考慮し、gtimeはできません.gtimeは時間の数(8時間)遅れを招く可能性があります.