티스토리 뷰

File

  • 보조기억장치에 저장된 연관된 정보들의 집합
    • 보조기억장치 할당의 최소 단위
    • Sequence of bytes (물리적 정의)
  • File operations
    • Create, Write, Read, Reposition, Delete Etc.
  • OS는 file operations들에 대한 system call을 제공해야 함

Types of files in Unix/Linux

  • Regular file 일반 파일
    • Text or binary data file
  • Directory
    • unix/linux에서는 directory도 하나의 파일
  • Special file
    • 파일 형태로 표현된 커널 내 객체
    • 데이터 전송, 장치 접근 시 사용하는 파일

Everything is a file

  • The advantage of this approach is that the same set of tools
  • ls -a: 숨겨진 모든 파일 목록 출력
    • .profile .viminfo 이런식으로 나옴
  • touch: 빈 파일 생성 or 파일의 time stamp 변경
  • rm: 파일 삭제
    • rm -r 디렉토리명: 이렇게 해야 디렉토리를 삭제할 수 있다.
  • cat: 파일 내용 출력
  • cp: 파일 복사
  • mv: 파일 이동, 이름 변경

File access permission

  • Owner, Group, others 사용자에 따라 read, write, execute 권한을 가짐
    • ex) drwxr-xr-x
  • chmod: 파일 권한 변경

Low-Level File IO

  • System call을 이용해서 파일 입출력 수행
  • File descriptor 사용
  • Byte 단위로 디스크에 입출력
  • 특수 파일에 대한 입출력 가능

High-Level File IO (Buffered IO)

  • C Standard library를 사용해서 파일 입출력 수행
  • File pointer 사용
  • 버퍼(block) 단위로 디스크에 입출력
    • 여러 형식의 입출력 지원

Opening files

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int open (const char *pathname, int flags [, mode_t mode]);
  • pathname (file path)
    • 열려는 파일의 경로(파일이름 포함)
  • flags
    • 파일을 여는 방법(access mode)
  • mode(file access permission)
    • 파일을 새로 생성 할 때만 유효
  • Return: file descriptor** (int 정수형태)

File descriptor

  • 열려 있는 파일을 구분하는 정수값
    • 특수 파일 등 대부분 파일을 지칭 가능
    • process 별로 kernel이 관리
  • 파일을 열 때 순차적으로 할당 됨
    • process 당 최대 fd 수 = 1024
  • Default fds (수정 가능)
    • 0: stdin
    • 1: stdout
    • 2: stderr

File table

  • 열린 파일을 관리하는 표
    • kernel이 process 별로 유지
    • 열린 파일에 대한 각종 정보 관리
      • Access mode, file offset, pointer to files
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
        int fd;
        mode_t mode;

        mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

        fd = open("hello.txt", O_CREAT, mode);
        if (fd == -1) {
                perror("Create"); exit(1);
        }
        close(fd);

        return 0;
}

fileOpenClose를 만들어서 컴파일하고 실행한 뒤 생성된 txt를 확인해보면 user는 r/w, group과 other는 r인 것을 확인할 수 있다.

 

O_EXCL: O_CREAT 옵션을 사용하는 경우 기존에 없는 파일이면 파일을 생성하지만 파일이 이미 있으면 파일을 생성하지 않고 오류 메시지를 출력한다. 이미 파일이 생성되어 있으므로 에러 메시지가 나온다.

 

Error handling for system call

  • system call 실패 시 -1 반환
  • Error code는 errno에 저장됨
    • error.h에 선언되어 있음
    • extern으로 직접 접근 가능
      • extern int errno;
  • perror(3)
    • Error message를 출력해주는 함수
int main(void) {
        int fd;

        fd = open("hello.txt", O_CREAT | O_EXCL, 0644);
        if (fd == -1) {
                perror("EXCL");
                exit(1);
        }
        close(fd);

        return 0;
}

 

컴퓨터 프로그램이 시작될 때, 기본적으로 3개의 파일 디스크립터가 자동으로 열립니다.

  • 0: 표준 입력 (stdin) - 키보드 입력
  • 1: 표준 출력 (stdout) - 화면 출력
  • 2: 표준 에러 (stderr) - 에러 메시지 출력
  • 3을 처음으로 사용 가능, close해서 3을 닫으면 3은 사용 가능한 상태가 됨.
  • close(0)으로 0은 사용 가능한 상태가 됨.
  • openfile 하게 되면 방금 닫은 0을 출력하게된다.

파일 디스크립터가 고정된 번호가 아니라, 운영체제가 관리하는 번호 자원 중에서 가장 낮은 번호를 순차적으로 할당받는다는 것을 명확히 보여줍니다.

 

출처: SPIN Lab. KOREATECH

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함