default behavior of who is to display a list of currently logged in users,
if there are no argument given when executing "who" command. it is basically reading from /var/run/utmp and write on terminal with appropriate format.
who process
- open the file /var/run/utmp
- read a utmp strcture untill end of file
- display the requried fields
- go to step2
- close file /var/run/utmp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <utmp.h>
#include <fcntl.h>
#include <time.h>
void show_info(struct utmp*);
int main(){
int fd = open("/var/run/utmp", O_RDONLY);
if (fd == -1 ){
perror("Error in opening utmp file");
exit(1);
}
struct utmp rec;
int reclen = sizeof(rec);
while (read(fd, &rec, reclen) == reclen)
show_info(&rec);
close(fd);
return 0;
}
void show_info(struct utmp *rec){
if(rec->ut_type != 7)
return;
printf("%-10.10s ", rec->ut_user);
printf("%-10.10s ", rec->ut_line);
long time = rec->ut_time;
char* dtg = ctime(&time);
printf("%-15.12s", dtg+4);
printf(" (%s)", rec->ut_host);
printf("\n");
}
work same as "who" command.
Buffering
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFSIZE 1024
int main(int argc, char *argv[]){
if (argc != 3) {
printf("Invalid number of arguments.\n");
exit(1);
}
int srcfd = open (argv[1], O_RDONLY);
int destfd = open(argv[2],O_CREAT|O_RDWR|O_TRUNC, 00600);
char buff[BUFSIZE];
int n = 0;
for(;;){
n = read (srcfd, buff, BUFSIZE);
if (n <= 0){
close(srcfd);
close(destfd);
return 0;
}
write(destfd, buff, n);
}
close(srcfd);
close(destfd);
return 0;
}
we can change Buffer size by changing marco define above.
with buffer we can read data with chunk. this case is user-space buffer
but kernel can also have buffer.
'Operating System > System Programming(Arif Butt)' 카테고리의 다른 글
Lec17) Process Management-I (0) | 2021.07.09 |
---|---|
Lec16) Programming Terminal Devices (0) | 2021.07.08 |
Lec14) Design and Code of UNIX ls Utility (0) | 2021.07.05 |
Lec13) UNIX File Management (0) | 2021.06.29 |
Lec12) UNIX File System Architecture (0) | 2021.06.27 |