본문 바로가기

Computer Science/System programing

[System programing] who, cp, buffering

0️⃣ Linux 로그파일

1. wtmp (/var/log/wtmp)
 : 성공한 로그인/로그아웃 정보 담고있는 로그파일
 $last 명령어 사용
2. utmp (/var/run/utmp)
 : 현재 로그인 사용자 상태정보를 담고있는 로그파일
 $w, $who, $finger 명령어 사용
3. btmp (/var/log/btmp)
  : 실패한 로그인 정보를 담고있는 로그파일
 

1️⃣ vi Editor

: Linux/Unix에서 사용되는 화면지향적 text 편집기
 
command mode와 insert mode가 있다
 ⦁  command mode
 : 시작할 때 사용되는 기본모드 / 파일 내 이동, 변경, 저장 등의 명령어
 ⦁  insert mode
 : 텍스트가 생성되는 모드 / <esc>키로 다시 command모드로 돌아간다.
 

2️⃣ who

: 호스트에 현재 로그인 중인 사용자 정보 리스트 출력

경로 : /usr/bin/who
output : 유저 이름, 터미널 정보, 로그인 시간, 호스트 또는 IP주소
How : 현재 접속한 사용자 정보를 /var/run/utmp 파일에서 가져옴.
 utmp파일 : 사용자가 원격으로 서버에 로그인 할 때 사용자 정보를 저장&사용자가 로그아웃 할 때 저장된 정보 삭제
 
📌 동작원리
open utmp -> [ read record -> display record ] -> close utmp
 
1. open
 : 프로세스와 파일 사이 연결 만듦 -> file descriptor / 파일 이름과 연결유형(r/w/r&w) 지정

include #include <fcntl.h>
usage int fd = open(char *name, int how)
args name   name of file
how     O_RDONLY, OREONLY, ORDWR
returns -1        on error
int        on success

2. read
 : 커널에게  file descriptor에서 호출 프로세스의 메모리 공간에 있는 array buf로 qty바이트의 데이터 전송 요청
   로그파일에서 받은 정보를 메모리 buf에 저장

include #include <unistd.h>
usage ssize_t numread = read(int fd, void *buf, size_t qty)
args fd        source of data
buf      destination for data
qty      number of bytes to transfer
returns -1             on error
numread  on success

3. close
 : file descriptor로부터의 연결 파괴

include #include <unistd.h>
usage int result = close(int fd)
args fd        file descriptor
returns -1       on error
0        on success

3️⃣ cp

: 파일 또는 디렉토리를 복사 / source-file을 target-file라는 이름으로 복사

$cp source-file target-file //경로 지정 없을 때는 현재 dir의 파일을, 경로가 있으면 함께 고려

 
📌 동작원리
open source-file for r -> open target-file for w -> [ read from source-file to buffer -> write from buffer to copy(eof까지 반복)] -> close source-file & copy-file
 
1. creat
 : 파일 또는 디렉토리를 생성

include #include <fcntl.h>
usage int fd = crear(char *filename, mode_t mode)
args filename   name of file
mode        access permision
returns -1       on error
fd       on success

2. write
 : 메모리의 데이터를 파일로 전송

include #include <unistd.h>
usage ssize_t result = write(int fd, void *buf, size_t amt)
args fd        a file descriptor
buf      an array
amt     how many bytes to write
returns -1               on error
num written   on success

 

4️⃣ Buffering

버터 크기가 클수록 적게 시스템을 호출해도 되고 = 시간이 적게 걸리고 = cost가 적게 든다고 볼 수 있다.

*시스템 호출에 시간이 소요되는 이유
1. data 전송을 위한 코드 실행
2. kernel과 user space 사이 이동
CPU는 kernel space에서 실행 / user code 실행시 user space로 실행
 
kernel buffring의 결과
1. 디스크 I/O 속도 향상 2. 최적화된 디스크 3. 종료 전 디스크에 버퍼 기록 필
 

+) lseek(), errno변수

로그아웃시 utmp파일의 기록이 변경됨
📌 로그에서 사용자 이름을 제거하는 프로그램 과정
1. utmp 파일 열기

fd = open(UTMP_FILE, O_RDWR); //읽기와 쓰기 권한 모두 필요

2. 내 터미널에 대한 기록 찾을 때가지 record 읽기

while( read(fd, rec, utmplen) == utmplen )  //내 기록 나올 때까지 읽어들이기
	if (strcmp(rec.ut_line, myline) == 0 )  //내 터미널과 같은 기록 찾기
    	revise_entry();  //같은 기록 있다면 삭제

3. 그 자리에 수정된 utmp 기록 대신 작성
write() 함수 이용해 기록 업데이트
-> 프로그램이 현재 읽기/쓰기 위치를 변경하기 위해 lseek() 호출 필요
 
4. utmp 파일 닫기

close(fd);

 
📌 lseek() 함수
 : 현재 위치(함수의 seek pointer(커서))를 이동할 때 사용
 : 열린 파일 fd의 현재 위치를 base를 기준으로 dist만큼 변경.

include #include <sys/types.h>
#include <unistd.h>
usage off_t oldpos = lseek(int fd, off_t dist, int base)
args fd        a file descriptor
dist     a distance in bytes //기준점으로부터 이동할 거리
base   SEEK_SET  => start of file
           SEEK_CUR => current position //현재 seek 포인터
           SEEK_END => end of file
returns -1       on error
or       the previous position in the file

📌 오류 코드를 알려주는 변수 errno
 return -1로 오류 발생을 알 수 있지만 그 종류 알 수 X -> 오류 원인이 담긴 변수 errno 사용
 
 

'Computer Science > System programing' 카테고리의 다른 글